给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
输入:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
输出:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
思路+代码+注释:
public static Node connect(Node root) {
/*
思路:递归遍历每个节点,p记录该节点的next指向的节点,扫描同级节点
p节点不为null,那么看p节点是否有左右子节点,如果有那么让p指向左右子节点,如果没有左右子节点那么p继续指向下一个next
如果当前节点有右子节点那么将右子节点的next设置为p
如果有左子节点,如果存有右子节点那么左子节点指向右子节点,否则指向p
*/
connect(root);
return root;
}
private void connectTree(Node root)
{
if (root==null)
{
return ;
}
Node p=root.next;
while (p!=null)
{
if (p.left!=null)
{
p=p.left;
break;
}
if (p.right!=null)
{
p=p.right;
break;
}
p=p.next;
}
if (root.right!=null)
{
root.right.next=p;
}
if (root.left!=null)
{
if (root.right!=null)
{
root.left.next=root.right;
}else {
root.left.next=p;
}
}
connectTree(root.right);
connectTree(root.left);
}