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
Tree Height and Depth ProblemINPUT: Binary Tree3920157Target: 15Array: [3,9,20,null,null,15,7]ALGORITHM: Single DFS1Start DFS from root2Track max depth (height)3Search for target node4Record target depth when foundCollected Information:✓ Tree Height: 2 (max depth)✓ Target Depth: 2 (found at level 2)RESULTOutput Array[2, 2][height, depth]Height: 2Target Depth: 2Key Insight:A single DFS traversal can simultaneously calculate tree height and locate target node depth,eliminating the need for multiple tree traversals and achieving optimal O(n) time complexity.TutorialsPoint - Tree Height and Depth | Single DFS Approach
Asked in
Google 28 Amazon 22 Microsoft 15 Facebook 12
25.6K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen