Tree Height and Depth - Problem
Given a binary tree and a target node value, calculate two important tree properties:
1. Height of the tree: The maximum distance from the root to any leaf node
2. Depth of the target node: The distance from the root to the node with the given value
Return an array [height, depth] where height is the tree height and depth is the depth of the target node. If the target node is not found, return [-1, -1].
Note: The root node is at depth 0. A single node tree has height 0.
Input & Output
Example 1 — Basic Binary Tree
$
Input:
root = [3,9,20,null,null,15,7], target = 15
›
Output:
[2,2]
💡 Note:
Tree height is 2 (root to leaf nodes 15 or 7). Target node 15 is at depth 2 (root→20→15).
Example 2 — Target at Root
$
Input:
root = [1,2,3], target = 1
›
Output:
[1,0]
💡 Note:
Tree height is 1 (root to leaves 2 or 3). Target node 1 is the root at depth 0.
Example 3 — Target Not Found
$
Input:
root = [5,3,8,1,4], target = 10
›
Output:
[-1,-1]
💡 Note:
Target node 10 does not exist in the tree, so return [-1,-1].
Constraints
- The number of nodes in the tree is in the range [0, 104]
- -109 ≤ Node.val ≤ 109
- -109 ≤ target ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code