LeetCode每日一题(117. Populating Next Right Pointers in Each Node II)

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

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

}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值