LeetCode 117. Populating Next Right Pointers in Each Node II - 二叉树系列题21

给定一个二叉树,填充每个节点的next指针,使其指向同一层的下一个节点。若无下一个节点,则指向NULL。此题要求使用常数额外空间,可以采用迭代的广度优先搜索(BFS)策略来解决。
摘要由CSDN通过智能技术生成

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.

给定一棵二叉树,该二叉树的节点结构除了节点值,左右子节点指针外,还有一个指针next,要求使每一个节点的next指向它所在层的右侧相邻的节点,如果节点已经是那一层的最右节点了那么next就指向空。 

涉及到二叉树层的概念,很自然会想到用水平遍历。二叉树水平遍历最常用的算法就是迭代法(BFS),即使用一个队列,从根节点开始每次把一层的节点放入队列中,在一次循环中,判断当前队列中节点个数(即当前层的节点个数)假设个数为n,依次从队列中取出一直到第n个节点,另外还需用一个指针始终指向当前节点的前一个节点,这样当前节点就是前一个节点在该层的右侧节点,只需把前一个节点的next指向当前节点。另外在处理每一个节点的同时判断其左右子节点是否存在,若存在就把它们放入队列中,这样当前层n个节点都处理完之后,队列中所有节点就是下一层的所有节点(这样就完成了一次迭代)。直到最后队列为空就表示整棵树处理完毕。

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return None
        q = deque([root])
        while q:
            n = len(q)
            pre = None
            for i in range(n):
                node = q.popleft()
                if pre:
                    pre.next = node
                pre = node
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        
        return root

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值