题目描述:
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
输入:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","left":{"id”:“2”,“left”:{“KaTeX parse error: Expected 'EOF', got '}' at position 53: …t":null,"val":4}̲,"next":null,"r…id”:“4”,“left”:null,“next”:null,“right”:null,“val”:5},“val”:2},“next”:null,“right”:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …null,"right":{"id”:“6”,“left”:null,“next”:null,“right”:null,“val”:7},“val”:3},“val”:1}
输出:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","left":{"id”:“2”,“left”:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …:null,"next":{"id”:“4”,“left”:null,“next”:{“KaTeX parse error: Expected 'EOF', got '}' at position 53: …t":null,"val":7}̲,"right":null,"…id”:“6”,“left”:null,“next”:null,“right”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"5"}̲,"val":3},"righ…ref”:“4”},“val”:2},“next”:null,“right”:{"$ref":“6”},“val”:1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
跟上一题思路差不多,只不过多了个寻找下一个节点的函数
但是题目中没有给出root.next = null 的定义这个有点奇怪???
因为本身就初始化为null
class Solution {
public Node connect(Node root) {
if (root == null) {
return null;
}
if (root.left != null) {
if (root.right != null) {
// 若右子树不为空,则左子树的 next 即为右子树
root.left.next = root.right;
} else {
// 若右子树为空,则右子树的 next 由根节点的 next 得出
root.left.next = nextNode(root.next);
}
}
if (root.right != null) {
// 右子树的 next 由根节点的 next 得出
root.right.next = nextNode(root.next);
}
// 先确保 root.right 下的节点的已完全连接,因 root.left 下的节点的连接
// 需要 root.left.next 下的节点的信息,若 root.right 下的节点未完全连
// 接(即先对 root.left 递归),则 root.left.next 下的信息链不完整,将
// 返回错误的信息。可能出现的错误情况如下图所示。此时,底层最左边节点将无
// 法获得正确的 next 信息:
// o root
// / \
// root.left o —— o root.right
// / / \
// o —— o o
// / / \
// o o o
connect(root.right);
connect(root.left);
return root;
}
private Node nextNode(Node node) {
while (node != null) {
if (node.left != null) {
return node.left;
}
if (node.right != null) {
return node.right;
}
node = node.next;
}
return null;
}
}