给定一个二叉树
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 所示。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
感谢生菜酸猪的递归解法,传送门递归法平凡版,无复杂指针,新手看。
感谢灵茶山艾府的三种方法:DFS/BFS/BFS+链表(附题单)Python/Java/C++/Go/JS
class Solution {
public Node connect(Node root) {
// return connectI(root);
// return connectII(root);
return connectIII(root);
}
//方法三:递归
//时间复杂度O(N),空间复杂度O(N)
private Node connectIII(Node root) {
if (root == null || (root.left == null && root.right == null)) {
return root;
}
//左右子树都有,左子树next右子树,右子树next指向当前层的下一个节点
if (root.left != null && root.right != null) {
root.left.next = root.right;
root.right.next = getNextNonNullNode(root);
}
//只有右子树,右子树next指向当前层的下一节点
if (root.left == null) {
root.right.next = getNextNonNullNode(root);
}
//只有左子树,左子树next指向当前层的下一节点
if (root.right == null) {
root.left.next = getNextNonNullNode(root);
}
//注意先递归右子树,否则右子树根节点的next关系没建立,左子树到右子树子节点无法正确挂载
connectIII(root.right);
connectIII(root.left);
return root;
}
//一路向右找到有子节点的根节点
private Node getNextNonNullNode(Node root) {
while (root.next != null) {
if (root.next.left != null) {
return root.next.left;
}
if (root.next.right != null) {
return root.next.right;
}
root = root.next;
}
return null;
}
//方法二:与116一样,利用队列BFS遍历
//时间复杂度O(N),空间复杂度O(N)
private Node connectII(Node root) {
if (root == null) {
return null;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
//前一个节点
Node prev = null;
while (size-- > 0) {
Node node = queue.poll();
//如果prev为空表示node是这一层的第一个节点,没有前一个节点指向它
//否则就让前一个节点指向它
if (prev != null) {
prev.next = node;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
prev = node;
}
}
return root;
}
//方法一:与116思路类似
//遍历当前层,将下一层的节点连接成链表
//时间复杂度O(N),空间复杂度O(1)
private Node connectI(Node root) {
if (root == null) {
return null;
}
Node cur = root;
while (cur != null) {
Node dummy = new Node(-1);
Node prev = dummy;
while (cur != null) {
if (cur.left != null) {
prev.next = cur.left;
prev = prev.next;
}
if (cur.right != null) {
prev.next = cur.right;
prev = prev.next;
}
//当前层链表的下一个节点
cur = cur.next;
}
//下一层链表的头节点
cur = dummy.next;
}
return root;
}
}