leetcode117. 填充每个节点的下一个右侧节点指针 II
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
借助116题填充每个节点的下一个右侧指针I的思路
先连接当前层的子节点,然后下一层就可以通过next找到想要的节点了。
但是这里注意:要先对右子树遍历,在while那里就可以看出来,如果先对左子树遍历,next指针是连不上的。
比如这个样例:
2
/ \
1 3
/ \ / \
0 7 9 1
/ / \ / \
2 1 0 8 8
/
7
在遍历到0的时候需要通过7->9->1的方法找到8,但是这个时候:
2
/ \
1 - -- > 3
/ \ / \
0 -> 7 ->9 1
/ / \ / \
2 1 -> 0 8 8
/
7
9和1没有next连上,先遍历右子树就能解决这种问题。
public Node connect(Node root) {
if(root==null)return null;
if(root.left!=null&&root.right!=null)
root.left.next=root.right;
Node tmp=null;
if(root.next!=null){
if(root.right!=null)tmp=root.right;
else if(root.left!=null)tmp=root.left;
Node p=root.next;
if(tmp!=null){
while(p!=null&&p.left==null&&p.right==null){
//System.out.print("while "+p.val);
p=p.next;
}
//System.out.println();
if(p!=null){
if(p.left!=null){
tmp.next=p.left;
}else{
tmp.next=p.right;
}
}
}
}
connect(root.right);
connect(root.left);
return root;
}
leetcode 39/100