leetcode-117. Populating Next Right Pointers in Each Node II

来源:互联网 发布:windows密码 编辑:程序博客网 时间:2024/05/22 08:04

leetcode-117. 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

和上一题不同。这里结构不是固定的了所以需要使用队列去保存当前的信息。而且有很多需要注意的小细节。

首先从思路上来说还是用FIFO的队列,并且每个循环体内都替换一次。直到到最后一行队列为空则终止循环。
外层循环每一层循环异常。内层循环针对当前对立的每个节点。

/** * Definition for binary tree with next pointer. * public class TreeLinkNode { *     int val; *     TreeLinkNode left, right, next; *     TreeLinkNode(int x) { val = x; } * } */public class Solution {    public void connect(TreeLinkNode root) {        if(root == null) return ;        LinkedList<TreeLinkNode> list = new LinkedList<TreeLinkNode>();        list.add(root);        while(list.size()!=0){            LinkedList<TreeLinkNode> replace = new LinkedList<TreeLinkNode>();            TreeLinkNode pre = list.remove();            if(pre.left!=null) replace.add(pre.left);            if(pre.right!=null) replace.add(pre.right);            TreeLinkNode cur = null;            while(list.size()!=0){                cur = list.remove();                if(cur!=null && cur.left!=null) replace.add(cur.left);                if(cur!=null && cur.right!=null) replace.add(cur.right);                pre.next = cur;                if(cur!=null) pre = cur;            }            if(replace.size()!=0) replace.add(null);            list = replace;        }    }}
0 0