题目描述
给定一个二叉树
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}
思路
1.思路与116. 填充每个节点的下一个右侧节点指针类似,都是上一层遍历连接下一层。
2.由于从满二叉树变成了二叉树,所以需要作出以下几个改动
- 设置每一层的头结点为亚结点,当亚结点的next为空时,结束遍历
- cur在连接结点前,需要先判断该结点是否为null
Java代码实现
public Node connect(Node root) {
Node cur = root;
Node p;
while(cur != null){
//每一层的头结点,是个亚结点
p = new Node();
Node head = p;
while(cur != null){
if(cur.left != null){
p.next = cur.left;
p = p.next;
}
if(cur.right != null){
p.next = cur.right;
p = p.next;
}
cur = cur.next;
}
//开始遍历下一层的结点
cur = head.next;
}
return root;
}