[LeetCode] Populating Next Right Pointers in Each Node II

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

 

 

Hide Tags
 Tree Depth-first Search
 
思路:接Populating Next Right Pointers in Each Node 还是如果当前层所有结点的next 指针已经设置好了,那么据此,下一层所有结点的next指针 也可以依次被设置。
只是,如何找到下一层最左侧的节点,以及如何找到自己节点右边的节点的最左节点需要麻烦些,我自己写了个findLeftMostOfNextLayer
class Solution {
    public:
        TreeLinkNode* findLeftMostOfNextLayer(TreeLinkNode * root)
        {
            if(root == NULL)
                return NULL;
            if(root->left)
                return root->left;
            if(root->right)
                return root->right;
            return findLeftMostOfNextLayer(root->next);
        }


        void connect(TreeLinkNode *root)
        {
            if(root == NULL)
                return;

            TreeLinkNode* curLayer = root;//the leftmost node of the layer

            while(curLayer)
            {
                TreeLinkNode* curNode = curLayer ;
                while(curNode)
                {
                    TreeLinkNode* left = curNode->left;
                    TreeLinkNode* right= curNode->right;
                    TreeLinkNode* next = findLeftMostOfNextLayer(curNode->next);
                    //curNode is not a leaf node
                    if(left && right)
                    {
                        left->next = right;
                    }

                    if(next)
                    {
                        if(right)
                            right->next = next;
                        else if(left)
                            left->next = next;
                    }
                    curNode = curNode->next;
                }
                curLayer = findLeftMostOfNextLayer(curLayer);

            }
        }
};

 

posted @ 2015-04-10 17:04  穆穆兔兔  阅读(203)  评论(0编辑  收藏  举报