首页 > 其他 > 详细

117. Populating Next Right Pointers in Each Node II (Tree; WFS)

时间:2015-10-04 15:52:22      阅读:235      评论:0      收藏:0      [点我收藏+]

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /        2    3
     / \        4   5    7

After calling your function, the tree should look like:

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

 

class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode* parent;
        TreeLinkNode* current;
        TreeLinkNode* nextParent = root;
   
        while(1){
           parent = nextParent;
           nextParent = NULL;
           while(parent){ //find nextParent
               if(parent->left) {
                   nextParent = parent->left;
                   break;
               }
               if(parent->right){
                   nextParent = parent->right;
                   break;
               }
               parent = parent->next;
           } 
           current = nextParent;
           if(!current) return;
   
           while(parent){
               if(current == parent->left){//add next pointer of left child
                   if(parent->right) current->next = parent->right;
                   else{ //find next until parent equals null
                       parent = parent->next;
                       while(parent){ 
                           if(parent->left) {
                               current->next = parent->left;
                               break;
                           }
                           if(parent->right){
                               current->next = parent->right;
                               break;
                           }
                           parent = parent->next;
                       }
                   }
               }
               else{ //add next pointer of right child
                   parent = parent->next;
                   while(parent){ //find next until parent equals null
                       if(parent->left) {
                           current->next = parent->left;
                           break;
                       }
                       if(parent->right){
                           current->next = parent->right;
                           break;
                       }
                       parent = parent->next;
                   }
               }
               current = current->next;
           } // end of level
        }
    }
};

 

117. Populating Next Right Pointers in Each Node II (Tree; WFS)

原文:http://www.cnblogs.com/qionglouyuyu/p/4854562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!