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

Leetcode Populating Next Right Pointers in Each Node II

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

标签:style   blog   color   strong   art   cti   

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

标签:style   blog   color   strong   art   cti   

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

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