Skip to content

1602. Find Nearest Right Node in Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) {
    TreeNode* ans = nullptr;
    int targetDepth = -1;
    dfs(root, u, 0, targetDepth, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* root, TreeNode* u, int depth, int& targetDepth,
           TreeNode*& ans) {
    if (root == nullptr)
      return;
    if (root == u) {
      targetDepth = depth;
      return;
    }
    if (depth == targetDepth && ans == nullptr) {
      ans = root;
      return;
    }
    dfs(root->left, u, depth + 1, targetDepth, ans);
    dfs(root->right, u, depth + 1, targetDepth, ans);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
    dfs(root, u, 0);
    return ans;
  }

  private TreeNode ans = null;
  private int targetDepth = -1;

  private void dfs(TreeNode root, TreeNode u, int depth) {
    if (root == null)
      return;
    if (root == u) {
      targetDepth = depth;
      return;
    }
    if (depth == targetDepth && ans == null) {
      ans = root;
      return;
    }
    dfs(root.left, u, depth + 1);
    dfs(root.right, u, depth + 1);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
  def findNearestRightNode(
      self,
      root: TreeNode,
      u: TreeNode,
  ) -> TreeNode | None:
    ans = None
    targetDepth = -1

    def dfs(root: TreeNode, depth: int) -> None:
      nonlocal ans
      nonlocal targetDepth
      if not root:
        return
      if root == u:
        targetDepth = depth
        return
      if depth == targetDepth and not ans:
        ans = root
        return
      dfs(root.left, depth + 1)
      dfs(root.right, depth + 1)

    dfs(root, 0)
    return ans