1.题目描述:
2.层序遍历:代码与leetcode116. 填充每个节点的下一个右侧节点指针一摸一样,这种解法与二叉树的形状无关。
class Solution {
public Node connect(Node root) {
if (root == null) return root;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
Node pre = new Node();
while (size > 0) {
Node temp = queue.poll();
size--;
if (size == 0) temp.next = null;//可省略
pre.next = temp;
pre = temp;
if (temp.left != null) queue.offer(temp.left);
if (temp.right != null) queue.offer(temp.right);
}
}
return root;
}
}
3.直接迭代:每一层借助链表的方式实现连接,详见注释。
class Solution {
public Node connect(Node root) {
if(root == null)return root;
Node cur = root;
while(cur != null){
Node temp = new Node();
Node dummy = temp;//用一个虚拟头节点标注下一层的链表开始
while(cur != null){//操作下一行使其连接
if(cur.left != null){
temp.next = cur.left;//看成链表连接
temp = temp.next;
}
if(cur.right != null){
temp.next = cur.right;
temp = temp.next;
}
cur = cur.next;//cur是当前行挪动,temp是下一行挪动拼接
}
cur = dummy.next;//挪动到下一层
}
return root;
}
}