1602. Find Nearest Right Node in Binary Tree

Find Nearest Right Node in Binary Tree - LeetCode

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.

  • code
class Solution:
    def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]:
        level = [root]
        while level:
            for i, cur in enumerate(level):
                if cur == u:
                    if i == len(level) - 1: return None
                    return level[i + 1]
            
            level = [i for node in level for i in (node.left, node.right) if i]