Skip to content

Commit 9bc4547

Browse files
committed
Solution for Maximum Depth of Binary Tree #227
Refactor maxDepth method and simplify dfs parameters for clarity
1 parent c97dba2 commit 9bc4547

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
17+
// Good solution from Leetcode
18+
// class Solution{
19+
// public int maxDepth(TreeNode root){
20+
// if (root==null) return 0;
21+
// return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
22+
// }
23+
// }
24+
25+
class Solution {
26+
// TC : O(n)
27+
// SC : O(h) height of tree(DFS), width of tree(BFS)
28+
public int maxDepth(TreeNode root) {
29+
return dfs(root, 0);
30+
}
31+
32+
private int dfs(TreeNode cursor, int depth) {
33+
if (cursor == null) {
34+
return depth;
35+
}
36+
return Math.max(
37+
dfs(cursor.left, depth + 1),
38+
dfs(cursor.right, depth + 1));
39+
}
40+
}

0 commit comments

Comments
 (0)