Input: Binary Tree =[1,2,3,null,4], Node =4Output: 2Explanation: The binary tree can be represented as:1/\23\4 Node 4is at depth 2(edges from root:1->2->4).
Input: Binary Tree =[1,2,3,null,null], Node =5Output: -1Explanation: The binary tree can be represented as:1/\23 Node 5 does not exist in the tree, so the result is-1.
classSolution {
publicstaticintfindDepth(TreeNode root, int target) {
return dfsHelper(root, target, 0);
}
privatestaticintdfsHelper(TreeNode node, int target, int currentDepth) {
if (node ==null) return-1; // Base case: Node is not foundif (node.val== target) return currentDepth; // Target node found// Check left and right subtreesint left = dfsHelper(node.left, target, currentDepth + 1);
if (left !=-1) return left; // Found in left subtreeint right = dfsHelper(node.right, target, currentDepth + 1);
return right; // Found in right subtree or not found (-1) }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
deffindDepth(self, root, target):
defdfs(node, current_depth):
ifnot node: # Base case: Node not foundreturn-1if node.val == target: # Target node foundreturn current_depth
# Search in left subtree left = dfs(node.left, current_depth +1)
if left !=-1: # Found in left subtreereturn left
# Search in right subtreereturn dfs(node.right, current_depth +1)
return dfs(root, 0)