LeetCode - Populating Next Right Pointers in Each Node

6691 단어 LeetCode
Populating Next Right Pointers in Each Node
2014.1.8 05:59
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

    Solution:
      It looks like this problem is somewhat related to level-order traversal, but the space limit cannot meet the requirement. You can't use constant space to do a level-order traversal. So we'll do it the preorder way.
      Left node is next to the right node, while the right node is next to the leftest node you can find on the same level right to this right node.
      Well... I guess the code is better explanation for this problem. I wouldn't waste more words than code to show what I'm doing. Please see the codes below.
      Time and space complexities are both O(n), where n is the number of nodes in the tree.
    Accepted code:
     1 // 1AC, nice
    
     2 /**
    
     3  * Definition for binary tree with next pointer.
    
     4  * struct TreeLinkNode {
    
     5  *  int val;
    
     6  *  TreeLinkNode *left, *right, *next;
    
     7  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
    
     8  * };
    
     9  */
    
    10 class Solution {
    
    11 public:
    
    12     void connect(TreeLinkNode *root) {
    
    13         // IMPORTANT: Please reset any member data you declared, as
    
    14         // the same Solution instance will be reused for each test case.
    
    15         if(root == nullptr){
    
    16             return;
    
    17         }
    
    18         
    
    19         // This algorithm won't work if the tree is not perfect.
    
    20         if(root->left){
    
    21             TreeLinkNode *ll, *rr;
    
    22             
    
    23             ll = root->left;
    
    24             rr = root->right;
    
    25             while(ll != nullptr){
    
    26                 ll->next = rr;
    
    27                 ll = ll->right;
    
    28                 rr = rr->left;
    
    29             }
    
    30         }
    
    31         connect(root->left);
    
    32         connect(root->right);
    
    33     }
    
    34 };

    좋은 웹페이지 즐겨찾기