runnig

Populate Next Pointer in Binary Tree

Feb 2nd, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. // http://leetcode.com/onlinejudge#question_116
  2. /*
  3. Given a binary tree
  4.  
  5.     struct TreeLinkNode {
  6.       TreeLinkNode *left;
  7.       TreeLinkNode *right;
  8.       TreeLinkNode *next;
  9.     }
  10. 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.
  11.  
  12. Initially, all next pointers are set to NULL.
  13.  
  14. Note:
  15.  
  16. You may only use constant extra space.
  17. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
  18. For example,
  19. Given the following perfect binary tree,
  20.          1
  21.        /  \
  22.       2    3
  23.      / \  / \
  24.     4  5  6  7
  25. After calling your function, the tree should look like:
  26.          1 -> NULL
  27.        /  \
  28.       2 -> 3 -> NULL
  29.      / \  / \
  30.     4->5->6->7 -> NULL
  31.  
  32. */
  33. class Solution {
  34. public:
  35.     void connect(TreeLinkNode *root) {
  36.         // Start typing your C/C++ solution below
  37.         // DO NOT write int main() function
  38.         if(!root) { return; }
  39.         reset(root);
  40.         connectImpl(root);
  41.     }
  42.    
  43.     void connectImpl(TreeLinkNode * n)
  44.     {
  45.         if(!n) { return; }
  46.        
  47.         TreeLinkNode * L = n->left, * R = n->right;
  48.        
  49.         if(!L || !R) { return; }
  50.        
  51.        
  52.         for(; L != NULL && R != NULL; L = L->right, R = R->left)
  53.         {
  54.             L->next = R;
  55.         }
  56.        
  57.         connectImpl(n->left);
  58.         connectImpl(n->right);
  59.     }
  60.    
  61.    
  62.     void reset(TreeLinkNode* n )
  63.     {
  64.         if(!n) { return; }
  65.         n->next = NULL;
  66.         reset(n->left);
  67.         reset(n->right);
  68.     }
  69. };
Advertisement
Add Comment
Please, Sign In to add comment