Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with ‘#’ signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 6000].
- -100 <= Node.val <= 100
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
既然是对同一层级的 node 之间的相互操作, 首先想到的肯定是 bfs, 用一个数组(nodes)保存当前层级的所有 node, 然后将 nodes[i].Next 设置为 nodes[i+1]即可, 同时我们还要将 nodes[i].Left 和 nodes[i].Right 放到下一层级的数组当中
func connect(root *Node) *Node {
stack := []*Node{root}
for len(stack) > 0 {
nexts := make([]*Node, 0, 2*len(stack))
for i := 0; i < len(stack)-1; i++ {
if stack[i] != nil {
stack[i].Next = stack[i+1]
if stack[i].Left != nil {
nexts = append(nexts, stack[i].Left)
}
if stack[i].Right != nil {
nexts = append(nexts, stack[i].Right)
}
}
}
last := stack[len(stack)-1]
if last != nil {
if last.Left != nil {
nexts = append(nexts, last.Left)
}
if last.Right != nil {
nexts = append(nexts, last.Right)
}
}
stack = nexts
}
return root
}

该博客介绍了如何使用广度优先搜索(BFS)策略来连接二叉树中同一层级的节点,使得每个节点的next指针指向其右侧的节点。在给定的代码实现中,通过维护一个栈来遍历每一层的节点,并将next指针正确设置。此外,代码还考虑了处理空节点的情况,确保了额外空间的常数复杂度。
437

被折叠的 条评论
为什么被折叠?



