Populating Next Right Pointers in Each Node II (LeetCode)

Question:

https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

 

解答:

本来想跟I一样,只不过把right->next从node->next->left换成node->next列当中碰到的第一个child节点。但是时间过界了。没明白问题具体在哪。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (!root)
            return;
            
        if (!root->left && !root->right)
            return;

        TreeLinkNode* rightChildNext = NULL;
        
        TreeLinkNode* next = root->next;
        
        while (next)
        {
            if (next->left || next->right)
            {
                rightChildNext = next->left ? next->left : next->right;
                break;
            }
            next = next->next;
        }
            
        if (root->right)
        {
            root->right->next = rightChildNext;
        }
            
        if (root->left)
        {
            root->left = root->right ? root->right : rightChildNext;
        }
        
        if (root->right)
            connect(root->right);
            
        if (root->left)
            connect(root->left);
    }

 

所以想到能不能用BFS代替DFS,先把一层的next都设好了,再处理下一层。因为每一层的节点都用next关联着的,所以只需要知道该层最左边的节点即可。

从最左边node开始一直到最右边(next->next->next...)往下找每一个子节点,如果找到一个,就把前一个子节点的next设成当前子节点。

 

    void connectCurrLevel(TreeLinkNode* parentleftMost)
    {
        if (!parentleftMost)
            return;
            
        TreeLinkNode* leftMostCurr = NULL;
        TreeLinkNode* prev = NULL;
        
        TreeLinkNode* next = parentleftMost;
        while (next)
        {
            if (next->left)
            {
                if (prev)
                    prev->next =next->left;
                else
                    leftMostCurr = next->left;

                prev = next->left;
            }
            
            if (next->right)
            {
                if (prev)
                    prev->next =next->right;
                else
                    leftMostCurr = next->right;

                prev = next->right;
            }
            
            next = next->next;
        }
        
        connectCurrLevel(leftMostCurr);
    }

 

posted @ 2014-10-26 14:24  smileheart  阅读(140)  评论(0)    收藏  举报