LeetCode 1602. Find Nearest Right Node in Binary Tree Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1602. Find Nearest Right Node in Binary Tree

Description

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.

Solutions

Solution 1: BFS

We can use Breadth-First Search, starting from the root node. When we reach node u, we return the next node in the queue.

The time complexity is O(n), and the space complexity is O(n). Where n is the number of nodes in the binary tree.

PythonJavaC++GoJavaScript
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: q = deque([root]) while q: for i in range(len(q) - 1, -1, -1): root = q.popleft() if root == u: return q[0] if i else None if root.left: q.append(root.left) if root.right: q.append(root.right)(code-box)

Solution 2: DFS

DFS performs a pre-order traversal of the binary tree. The first time we search to node u, we mark the current depth d. The next time we encounter a node at the same level, it is the target node.

The time complexity is O(n), and the space complexity is O(n). Where n is the number of nodes in the binary tree.

PythonJavaC++GoJavaScript
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: def dfs(root, i): nonlocal d, ans if root is None or ans: return if d == i: ans = root return if root == u: d = i return dfs(root.left, i + 1) dfs(root.right, i + 1) d = 0 ans = None dfs(root, 1) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !