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