runnig

[leetcode] 117 Populate Next Pointer in Binary Tree II

Feb 3rd, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<TreeLinkNode*> lonely;
  4.     int Depth;
  5.    
  6.     void clean_next(TreeLinkNode * root)
  7.     {
  8.         if(!root) { return; }
  9.        
  10.         root->next = NULL;
  11.        
  12.         clean_next(root->left);
  13.         clean_next(root->right);
  14.     }
  15.    
  16.     int depth(TreeLinkNode * root)
  17.     {
  18.         if(!root) { return 0; }
  19.         return max(depth(root->left), depth(root->right))+1;
  20.     }
  21.    
  22.     void connect(TreeLinkNode *root) {
  23.         if(!root) { return; }
  24.        
  25.         Depth = depth(root);
  26.         lonely.resize(Depth+1, NULL);
  27.        
  28.         clean_next(root);        
  29.         connect_impl(root, 0);
  30.     }
  31.    
  32.     void connect_impl(TreeLinkNode * root, const int depth)
  33.     {
  34.         if(!root) { return; }
  35.        
  36.         TreeLinkNode * L = root->left;
  37.         TreeLinkNode * R = root->right;
  38.        
  39.         int d = depth + 1;
  40.         for(; L || R ; ++d)
  41.         {            
  42.             TreeLinkNode * n = lonely[d];
  43.                    
  44.             if(L)
  45.             {                  
  46.                 if(n != NULL && n->next == NULL)
  47.                 {
  48.                     n->next = L;
  49.                 }
  50.            
  51.                 if(R)
  52.                 {
  53.                     L->next = R;
  54.                 }
  55.                 else
  56.                 {
  57.                     lonely[d] = L;
  58.                 }
  59.                 L = L->right ? L->right : L->left;
  60.             }
  61.            
  62.             if(R)
  63.             {
  64.                 if(n != NULL && n->next == NULL)
  65.                 {
  66.                     n->next = R;
  67.                 }
  68.                 lonely[d] = R;
  69.                
  70.                 R = R->left ? R->left : L->right;                
  71.             }              
  72.         }        
  73.         connect_impl(root->left, depth+1);
  74.         connect_impl(root->right, depth+1);
  75.     }
  76. };
Advertisement
Add Comment
Please, Sign In to add comment