给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
方法一:普通层序遍历
与#116做法一致,但效率偏低,这里不做演示。
方法二:升级层序遍历
class Solution {
public Node connect(Node root) {
if(root == null)return null;
Node cur = root;
while(cur != null) {
Node dummy = new Node(0);
Node pre = dummy;
while(cur != null) {
if(cur.left != null) {
pre.next = cur.left;
pre = pre.next;
}
if(cur.right != null) {
pre.next = cur.right;
pre = pre.next;
}
cur = cur.next;
}
cur = dummy.next;
}
return root;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii