LeetCode OJ:Populating Next Right Pointers in Each Node II(指出每一个节点的下一个右侧节点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

指出每个节点的下一个右侧节点,前一篇博客的那个思路也可以继续使用,但由于这里的二叉树是任意的,所以应该用函数找到下一层的开始节点以及下一层的下一个节点,代码如下:

 1 class Solution{
 2 public:
 3     void connect(TreeLinkNode *root)
 4     {
 5         TreeLinkNode * prev, * curr, * start;        
 6         if(!root) return;
 7         while(root){
 8             start = findNextLevelStartNode(root);
 9             prev = start;
10             curr = findNextLevelNextNode(root, prev);
11             while(curr){
12                 prev->next = curr;
13                 prev = curr;
14                 curr = findNextLevelNextNode(root, curr);
15             }
16             root = start;
17         }
18     }
19 private:
20     TreeLinkNode * findNextLevelNextNode(TreeLinkNode * & node, TreeLinkNode * curr)//注意使用引用
21     {
22         if(node->left == curr && node->right)
23             return node->right;
24         else{
25             while(node->next){
26                 node = node->next;
27                 if(node->left != NULL && node->left != curr) return node->left;
28                 if(node->right != NULL && node->right != curr) return node->right;
29             }
30         }
31         return NULL;
32     }
33 
34     TreeLinkNode * findNextLevelStartNode(TreeLinkNode * node)
35     {
36         if(!node) return NULL;
37         if(node->left)
38             return node->left;
39         else return findNextLevelNextNode(node, node->left);
40     }
41 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4915789.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值