[LeetCode] 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 toNULL.

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

 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 convert(TreeLinkNode *root)
12     {
13         if (root == NULL)
14             return;
15             
16         TreeLinkNode *leftNode = root->left;
17         TreeLinkNode *rightNode = root->right;
18         
19         if (leftNode && rightNode)
20         {
21             leftNode->next = rightNode;
22             rightNode->next = NULL;
23             TreeLinkNode *rightChild = leftNode->right;
24             TreeLinkNode *leftChild = rightNode->left;
25             if (leftChild && rightChild)
26                 leftChild->next = rightChild;                
27         }
28         
29         connect(leftNode);
30         connect(rightNode);        
31     }
32     
33     void fix(TreeLinkNode *leftNode, TreeLinkNode *rightNode)
34     {
35         if (leftNode == NULL)
36             return;
37             
38         leftNode->next = rightNode;
39         
40         fix(leftNode->right, rightNode->left);
41     }
42     
43     void connect(TreeLinkNode *root) {
44         // Start typing your C/C++ solution below
45         // DO NOT write int main() function
46         if (root == NULL)
47             return;
48             
49         convert(root);
50         fix(root->left, root->right);
51     }
52 };
posted @ 2012-11-25 14:13  chkkch  阅读(805)  评论(0编辑  收藏  举报