LeetCode OJ:Populating Next Right Pointers in Each Node(指出每一个节点的下一个右侧节点)

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
       /  
      2    3
     /   / 
    4  5  6  7

After calling your function, the tree should look like:

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

这题首先想到的当然是用bfs来做,但是题目只允许使用常数量的额外空间,用queue肯定是无法实现的,那么可以采取先序遍历的方式,由于是完全二叉树,所以有左孩子那么就一定也有右孩子了,所以递归的时候注意这点就可以了。下面是代码:

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         preorderTranversal(root);
 5     }   
 6 
 7     void preorderTranversal(TreeLinkNode *root)
 8     {
 9         if(!root || !root->left) return;
10         root->left->next = root->right;
11         if(root->next)
12             root->right->next = root->next->left;//这一步的连接应该注意一下
13         preorderTranversal(root->left);
14         preorderTranversal(root->right);
15     }
16 };

 当然这题也可以使用非递归的方法来实现,非递归方法代码如下所示:

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if(root == NULL) return ;
13         while(root->left){
14             TreeLinkNode * tmpRoot = root;
15                 tmpRoot->left->next = tmpRoot->right;
16             while(tmpRoot->next){
17                 tmpRoot->right->next = tmpRoot->next->left;
18                 tmpRoot = tmpRoot->next;
19                 if(tmpRoot->left)
20                     tmpRoot->left->next = tmpRoot->right;
21             }
22             root = root->left;
23         }
24     }
25 };
原文地址:https://www.cnblogs.com/-wang-cheng/p/4914246.html