【ATT】Populating Next Right Pointers in Each Node II

Q: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

A:  非平衡二叉树,右子树可能为空,重点在于right->left遍历

    TreeLinkNode* getNearbyNext(TreeLinkNode* root)
    {
        root = root->next;
        while(root)
        {
            if(!root->left&&!root->right)
                root = root->next;
            else
                return (root->left?root->left:root->right);
        }
        return NULL;
    }
    void connect(TreeLinkNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if(!root||(!root->left&&!root->right))  //null or leaf
            return;
            
        if(root->left&&root->right)
        {
            root->left->next = root->right;
            root->right->next = getNearbyNext(root);
        }else if(root->left&&!root->right)
        {
            root->left->next = getNearbyNext(root);
        }else if(!root->left&&root->right)
        {
           root->right->next = getNearbyNext(root);
        }
        connect(root->right);   //from right to left
        connect(root->left);
        
    }

  

posted @ 2013-06-17 21:08  summer_zhou  阅读(202)  评论(0编辑  收藏  举报