Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
/ \
2 3
/ \ \
4 5 7

After calling your function, the tree should look like:

         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL

解法一:

先使用队列进行BFS(O(n)),队列中的节点还需要存放当前所在层数。

如果前一个遍历到的节点pre与当前遍历到的节点cur不在同一层,那么pre->next需要指向NULL

如果在同一层,那么pre->next = cur

/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
struct Node
{
TreeLinkNode* tree;
int level;
Node(TreeLinkNode* root, int l):tree(root),level(l) {}
}; class Solution {
public:
queue<Node*> q;
void connect(TreeLinkNode *root)
{
if(root == NULL)
return; Node* rootNode = new Node(root, );
q.push(rootNode); Node *cur = rootNode;
Node *pre = rootNode;
Node *temp = rootNode; while(!q.empty())
{
temp = q.front();
q.pop(); if(temp->tree->left)
{
Node* leftNode = new Node(temp->tree->left, temp->level+);
q.push(leftNode);
pre = cur;
cur = leftNode;
if(pre->level < cur->level)
//get to next level
pre->tree->next = NULL;
else
//still same level
pre->tree->next = cur->tree;
}
if(temp->tree->right)
{
Node* rightNode = new Node(temp->tree->right, temp->level+);
q.push(rightNode);
pre = cur;
cur = rightNode;
if(pre->level < cur->level)
//get to next level
pre->tree->next = NULL;
else
//still same level
pre->tree->next = cur->tree;
}
}
}
};

解法二:

稍作分析就可以发现,我们没有必要像BFS那样存储整个一层的节点。

只需要保留三个信息:下一层的头levelHead,本层的上一个节点prev,本层的当前节点cur即可

对于每一层来说,prev的next连接cur。当本层遍历完,通过levelHead进入下一层。

/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root)
{
TreeLinkNode* cur = root; //node being visited
TreeLinkNode* levelHead = NULL; //first node in the next level
TreeLinkNode* prev = NULL; //last visited node while(cur)
{//there remains levels to be visited
while(cur)
{//there remains nodes to be visited in this level
if(cur->left)
{
if(prev)
{//cur->left is not the levelHead, link it to the prev
prev->next = cur->left;
}
else
{//cur->left is the levelHead
levelHead = cur->left;
}
prev = cur->left;
}
if(cur->right)
{
if(prev)
{//cur->right is not the levelHead, link it to the prev
prev->next = cur->right;
}
else
{//cur->right is the levelHead
levelHead = cur->right;
}
prev = cur->right;
}
cur = cur->next; //travel through this level
} cur = levelHead; //travel to the next level
levelHead = NULL;
prev = NULL;
}
}
};

【LeetCode】117. Populating Next Right Pointers in Each Node II (2 solutions)的更多相关文章

  1. 【LeetCode】117. Populating Next Right Pointers in Each Node II 解题报告(Python)

    [LeetCode]117. Populating Next Right Pointers in Each Node II 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

  2. 【一天一道LeetCode】#117. Populating Next Right Pointers in Each Node II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Follow ...

  3. Leetcode 笔记 117 - Populating Next Right Pointers in Each Node II

    题目链接:Populating Next Right Pointers in Each Node II | LeetCode OJ Follow up for problem "Popula ...

  4. 【LeetCode】115. Populating Next Right Pointers in Each Node (2 solutions)

    Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode * ...

  5. 【LeetCode】116. Populating Next Right Pointers in Each Node

    题目: Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode ...

  6. LeetCode OJ 117. Populating Next Right Pointers in Each Node II

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  7. leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II

    leetcode 199. Binary Tree Right Side View 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...

  8. leetcode@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)

    https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ Follow up for problem ...

  9. Java for LeetCode 117 Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

随机推荐

  1. MongoDB基础学习(一) MongoDB概念解析

    .基础概念 SQL术语/概念 MongoDB术语/概念 说明 database database 数据库 table collection 数据表/集合 row document 数据记录行/文档 c ...

  2. ECMAScript5严格模式

    ECMAScript5引入了严格模式(strict mode)的概念,IE10+开始支持.严格模式为JavaScript定义了一种不同的解析和执行模型,在严格模式下,ECMAScript3中的一些不确 ...

  3. Git配置非22端口,解决:ssh: connect to host xxx port 22: Connection timed out fatal: The remote end hung up unexpectedly

    背景:私自搭建了Git服务器,而Git本身就是SSH进行连接的,而Git命令上默认只能通过22端口实现. 解决方法: 第一种: 在系统的用户目录下的文件夹:.ssh 如果该路径下没有config文件, ...

  4. Linux下Shell命令的输出信息同时显示在屏幕和保存到日志文件中

    #直接覆盖日志文件 ls -l | tee ./t.log #将输出内容附加到日志文件 ls -l | tee -a ./t.log 使用的是tee命令

  5. ios/object-c中的UIColor一些比较偏的颜色展示/示例

    UIColor blackColor]; [UIColor darkGrayColor]; [UIColor lightGrayColor]; [UIColor grayColor]; [UIColo ...

  6. Current mirror drives multiple LEDs from a low supply voltage

    Driving LEDs at a regulated current from low supply voltages can be difficult because minimal overhe ...

  7. 关于GCC Cygwin MinGW MSYS

    [转载]关于Gcc/MinGW/Cygwin/Msys http://blog.sciencenet.cn/blog-778757-616920.html 一.GCC的历史 GCC是一个原本用于Uni ...

  8. ABC定制视图导航控制器

      ABCustomUINavigationController  ABC定制视图导航控制器   Subclass of UINavigationController for overwriting ...

  9. IIS7 win7 x64 MVC部署

    .net4.5已经装好,mvc4setup也装了,启动IIS后打开网页还是不能正常显示页面,404错误 最后发现把win7升级到SP1就正常了,具体是那个补丁修复的就不知道了

  10. 学习笔记 ST算法

    [引子]RMQ (Range Minimum/Maximum Query)问题: 对于长度为n的数列A,回答若干询问RMQ(A,i,j)(i,j<=n),返回数列A中下标在i,j里的最小(大)值 ...