码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Populating Next Right Pointers in Each Node II

时间:2014-11-29 11:45:49      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

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

 

先使用队列进行BFS(O(n)),队列中的节点还需要存放当前所在层数。

如果前一个遍历到的节点pre与当前遍历到的节点cur不在同一层,那么pre->next需要指向NULL

如果在同一层,那么pre->next = cur

/**
 * 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) {}
 * };
 */
struct Node
{
    TreeLinkNode* tree;
    int level;
    Node(TreeLinkNode* root, int l):tree(root),level(l) {}
};

class Solution {
public:
    queue<Node*> q;
    void connect(TreeLinkNode *root) 
    {
        if(root == NULL)
            return;

        Node* rootNode = new Node(root, 0);
        q.push(rootNode);

        Node *cur = rootNode;
        Node *pre = rootNode;
        Node *temp = rootNode;

        while(!q.empty())
        {
            temp = q.front();
            q.pop();

            if(temp->tree->left)
            {
                Node* leftNode = new Node(temp->tree->left, temp->level+1);
                q.push(leftNode);
                pre = cur;
                cur = leftNode;
                if(pre->level < cur->level)
                //get to next level
                    pre->tree->next = NULL;
                else
                //still same level
                    pre->tree->next = cur->tree;
            }
            if(temp->tree->right)
            {
                Node* rightNode = new Node(temp->tree->right, temp->level+1);
                q.push(rightNode);
                pre = cur;
                cur = rightNode;
                if(pre->level < cur->level)
                //get to next level
                    pre->tree->next = NULL;
                else
                //still same level
                    pre->tree->next = cur->tree;
            }
        }
    }
};

bubuko.com,布布扣

【LeetCode】Populating Next Right Pointers in Each Node II

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/ganganloveu/p/4130414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!