您的位置:首页 > Web前端 > Node.js

[leetcode-116]Populating Next Right Pointers in Each Node(c++)

2015-08-12 09:08 627 查看
问题描述:

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

分析:这道题比上一题稍微复杂一点,因为这里面不一定是完全二叉树,不过思路是一样的。只是需要加一个函数,来找到下一个要链接的node。

迭代法(40ms)

[code]/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
    private:
        TreeLinkNode* cur;
        bool isLeft = true;
public:
    void connect(TreeLinkNode *root) {
        if(!root)
            return;
        while(1){
            cur = root;
            TreeLinkNode* nextLeft = findNextLevelNode();
            root = nextLeft;

            if(!nextLeft)
                break;
            TreeLinkNode* tmp;
            while((tmp=findNextLevelNode())!=NULL){
                nextLeft -> next = tmp;
                nextLeft = tmp;
            }
        }
    }
    TreeLinkNode* findNextLevelNode(){
        while(cur){
            if(isLeft && cur->left){
                isLeft = false; 
               return cur->left;
            }
           TreeLinkNode* val = cur->right;
            isLeft = true;
            cur = cur->next;
            if (val)
                return val;
        }
        return NULL;
    }
};


//使用BFS:40ms

[code]/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (!root)
            return;
        queue<TreeLinkNode *> queue;
        queue.push(root);
        int count = 1;

        while (!queue.empty()) {
            int tmpCount = 0;
            TreeLinkNode* head = NULL;
            for (int i = 0; i < count; i++) {
                TreeLinkNode* tmp = queue.front();
                queue.pop();

                if(tmp->left){
                    tmpCount++;
                    queue.push(tmp->left);
                }
                if(tmp->right){
                    tmpCount++;
                    queue.push(tmp->right);
                }

                if (!head)
                    head = tmp;
                else {
                    head->next = tmp;
                    head = tmp;
                }
            }
            count = tmpCount;
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: