medium Find maximum depth of subtree
Problem Statement
Given the root node of a binary tree and an integer val, find the maximum depth of the subtree that starts from the node with the value equal to val. If the node with value val doesn't exist in the tree, return 0.
The depth of a node is defined as the number of edges on the longest path from the node to a leaf.
Examples
Example 1
- Input: root =
[3, 5, 4, 2, null, 1, null, 6], val =5
- Expected Output:
3 - Explanation: The subtree starting from the node with value
5has nodes5,2, and6. The maximum depth of this subtree is3.
Example 2
- Input: root =
[1, 2, 3, 4, null, null, 5, 6], val =3
- Expected Output:
2 - Explanation: The subtree starting from the node with value
3has nodes3and5. The maximum depth of this subtree is2.
Example 3
- Input: root =
[7, 3, 9, 1, 6, null, 8, null, null, null, 2], val =3
- Expected Output:
3 - Explanation: The subtree starting from the node with value
3has nodes3,6, and2. The maximum depth of this subtree is3.
Try it yourself
Try solving this question here:
✅ Solution Find maximum depth of subtree
Problem Statement
Given the root node of a binary tree and an integer val, find the maximum depth of the subtree that starts from the node with the value equal to val. If the node with value val doesn't exist in the tree, return 0.
The depth of a node is defined as the number of edges on the longest path from the node to a leaf.
Examples
Example 1
- Input: root =
[3, 5, 4, 2, null, 1, null, 6], val =5
- Expected Output:
3 - Explanation: The subtree starting from the node with value
5has nodes5,2, and6. The maximum depth of this subtree is3.
Example 2
- Input: root =
[1, 2, 3, 4, null, null, 5, 6], val =3
- Expected Output:
2 - Explanation: The subtree starting from the node with value
3has nodes3and5. The maximum depth of this subtree is2.
Example 3
- Input: root =
[7, 3, 9, 1, 6, null, 8, null, null, null, 2], val =3
- Expected Output:
3 - Explanation: The subtree starting from the node with value
3has nodes3,6, and2. The maximum depth of this subtree is3.
Solution
To solve this problem, we need to locate the node in the binary tree that has the value equal to val. Once we find this node, the task is to determine the depth of the subtree rooted at this node. Depth in this context means the number of edges on the longest path from the node to any of its leaf nodes.
We will utilize Depth-First Search (DFS) to explore all possible paths from the root node until we find the desired node. After locating the node, we continue the DFS to measure the depth of the subtree. This approach is efficient for this problem because DFS will allow us to traverse deep into the tree, ensuring we account for all possible depths before concluding.
Step-by-Step Algorithm
Part 1: Finding the Node with Value val
-
Start at the root node:
- Begin the search from the root node of the tree.
-
Check if the tree is empty:
- If the
rootisnull, return0because the tree is empty.
- If the
-
Check if the current node's value matches
val:- Compare the value of the current node (
root.val) with the target valueval. - If they match, proceed to the next part to calculate the depth of the subtree.
- Compare the value of the current node (
-
Search in the left subtree:
- If the current node's value doesn't match
val, recursively search in the left subtree by calling the method onroot.left.
- If the current node's value doesn't match
-
Search in the right subtree:
- If the node is not found in the left subtree, recursively search in the right subtree by calling the method on
root.right.
- If the node is not found in the left subtree, recursively search in the right subtree by calling the method on
Part 2: Finding the Depth of the Subtree
-
Initialize the depth calculation at the found node:
- Once the node with value
valis found, start calculating the depth of the subtree rooted at this node.
- Once the node with value
-
Check if the current node is
null:- If the current node is
null, return0because a null node contributes no depth.
- If the current node is
-
Calculate the depth of the left subtree:
- Recursively call the depth calculation method on the left child of the current node.
-
Calculate the depth of the right subtree:
- Recursively call the depth calculation method on the right child of the current node.
-
Determine the maximum depth:
- For the current node, calculate the depth as
1 + max(leftDepth, rightDepth)whereleftDepthandrightDepthare the depths of the left and right subtrees, respectively.
- For the current node, calculate the depth as
-
Return the calculated depth:
- Return the depth calculated from the current node to its deepest leaf node, representing the depth of the subtree rooted at this node.
Algorithm Walkthrough
Input:
- Root:
[3, 5, 4, 2, null, 1, null, 6] - Val:
5
Step 1: Finding the Node with Value 5
-
Start at the root node with value
3:- The current node is
3. The value3does not matchval = 5. - Proceed to search in the left subtree of node
3.
- The current node is
-
Move to the left child of node
3, which is5:- The current node is now
5. The value5matchesval = 5. - We have found the node where the subtree starts.
- The current node is now
-
Proceed to calculate the depth of the subtree rooted at node
5:- Now that the node with value
5is found, we move on to calculating the depth of the subtree rooted at this node.
- Now that the node with value
Step 2: Calculating the Depth of the Subtree Rooted at Node 5
-
Calculate the depth of the left subtree of node
5:- Move to the left child of node
5, which is2. - To find the depth of the subtree rooted at
2, proceed to its left child.
- Move to the left child of node
-
Move to the left child of node
2, which is6:- The current node is
6. It has no left or right children, meaning it's a leaf node. - The depth of node
6is1because there are no further children.
- The current node is
-
Calculate the depth of node
2:- Node
2has a left depth of1(from node6) and no right child. - The depth of node
2is1 + max(1, 0) = 2.
- Node
-
Calculate the depth of the right subtree of node
5:- The right child of node
5isnull, so the right depth is0.
- The right child of node
-
Determine the maximum depth of node
5:- Node
5has a left depth of2(from node2) and a right depth of0. - The depth of node
5is1 + max(2, 0) = 3.
- Node
-
Return the depth of the subtree rooted at node
5:- The final output is
3, which represents the depth of the subtree starting from the node with value5.
- The final output is
Code
// Define the TreeNode class
// class TreeNode {
// int val; // Value of the node
// TreeNode left; // Left child of the node
// TreeNode right; // Right child of the node
// // Constructor to initialize the node with a value
// TreeNode(int val) {
// this.val = val;
// this.left = null;
// this.right = null;
// }
// }
// Define the Solution class
public class Solution {
// Method to find the maximum depth of the subtree that starts with the node having value `val`
public int maxDepthOfSubtree(TreeNode root, int val) {
// If the tree is empty, return 0
if (root == null) {
return 0;
}
// If the current node's value matches `val`, calculate the maximum depth from here
if (root.val == val) {
return findMaxDepth(root);
}
// Recursively search in the left and right subtrees
int leftDepth = maxDepthOfSubtree(root.left, val);
int rightDepth = maxDepthOfSubtree(root.right, val);
// Return the maximum depth found
return Math.max(leftDepth, rightDepth);
}
// Helper method to calculate the depth of a given subtree
private int findMaxDepth(TreeNode node) {
// If the node is null, return 0 as the depth
if (node == null) {
return 0;
}
// Recursively find the depth of the left and right subtrees
int leftDepth = findMaxDepth(node.left);
int rightDepth = findMaxDepth(node.right);
// The depth of the current node is 1 plus the maximum of the depths of its subtrees
return 1 + Math.max(leftDepth, rightDepth);
}
// Main method to test the solution with example inputs
public static void main(String[] args) {
// Example 1:
TreeNode root1 = new TreeNode(3);
root1.left = new TreeNode(5);
root1.right = new TreeNode(4);
root1.left.left = new TreeNode(2);
root1.right.left = new TreeNode(1);
root1.left.left.left = new TreeNode(6);
Solution solution1 = new Solution();
System.out.println(solution1.maxDepthOfSubtree(root1, 5)); // Output: 3
}
}
Complexity Analysis
-
Time Complexity: The time complexity of the solution is
, where Nis the number of nodes in the binary tree. This is because we may need to traverse all nodes in the tree to find the node with valuevaland then calculate the depth of the subtree starting from that node. -
Space Complexity: The space complexity is
, where His the height of the binary tree. This is due to the recursive depth-first search (DFS) approach, which will require stack space proportional to the height of the tree.
🤖 Don't fully get this? Learn it with Claude
Stuck on Find maximum depth of subtree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Find maximum depth of subtree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Find maximum depth of subtree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Find maximum depth of subtree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Find maximum depth of subtree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.