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 atroot
.
题目给定一棵二叉树和一个节点,要求找出给定节点所在的那一层中右侧离该节点最近的那个节点,如果给定节点已经是那一层最右侧的节点了就返回空节点。
根据题目描述,很显然是用水平遍历算法,我们常用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