LeetCode 1602. Find Nearest Right Node in Binary Tree - 二叉树(Binary Tree)系列题14

Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level.

Example 1:

Input: root = [1,2,3,null,4,5,6], u = 4
Output: 5
Explanation: The nearest node on the same level to the right of node 4 is node 5.

Example 2:

Input: root = [3,null,4,2], u = 2
Output: null
Explanation: There are no nodes to the right of 2.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 105
  • All values in the tree are distinct.
  • u is a node in the binary tree rooted at root.

题目给定一棵二叉树和一个节点,要求找出给定节点所在的那一层中右侧离该节点最近的那个节点,如果给定节点已经是那一层最右侧的节点了就返回空节点。 

根据题目描述,很显然是用水平遍历算法,我们常用BFS来实现水平遍历,用一个队列每次存放整层的节点,每次循环判断队列中节点个数,假设个数为n,那么当前层的节点个数就是n,当挨个从队列中取出节点时,要是遇到节点等于目标节点,如果这时节点不是取出的第n个节点,那么下一个取出的节点就是该层右侧离目标节点最近的节点;如果目标节点已经是第n个取出的节点,那么说明目标节点已经该层最右侧节点,直接返回空节点。

class Solution:
    def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]:
        if not root:
            return None
        
        q = deque([root])
        
        while q:
            n = len(q)
            for i in range(n):
                node = q.popleft()
                if node == u:
                    return q[0] if i < n - 1 else None
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        
        return None

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值