首页 > 其他 > 详细

Leetcode Populating Next Right Pointers in Each Node II

时间:2014-07-03 20:35:03      阅读:380      评论:0      收藏:0      [点我收藏+]

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

 题目看起来比较复杂,如果把它当做对二维数组建立链表,此时就容易想了

主要难点就是有上一层如何去控制下一层,你可以根据链表的思路,用一个dummy结点,每次指向新的一行,然后根据按照链表遍历思路,根据next结点去遍历,一边遍历一边添加下一层的结点。

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL) return;
        root->next =NULL;
        TreeLinkNode *start = root, *nextStart = new TreeLinkNode(0),*p = nextStart;
        while(start){
            if(start->left) {p->next = start->left;p = p->next;}
            if(start->right){p->next = start->right;p = p->next;}
            if(start->next ==NULL ){
                p->next = NULL;
                start = nextStart->next;
                p = nextStart;
            }else start = start->next;
        }
    }
};

 

 

Leetcode Populating Next Right Pointers in Each Node II,布布扣,bubuko.com

Leetcode Populating Next Right Pointers in Each Node II

原文:http://www.cnblogs.com/xiongqiangcs/p/3821128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!