Skip to content

Commit 11ad1cd

Browse files
committed
feat: max-depth-of-bin-tree
1 parent 6d518d9 commit 11ad1cd

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Intuition
2+
Recursuib is a natural method for iterating trees.
3+
4+
# Approach
5+
<!-- Describe your approach to solving the problem. -->
6+
1. Child function can calculate the depth of its subtrees automatically.
7+
2. Parent function only select the maximum of the two depths and return +1. (i.e. `+1` means parent's depth.)
8+
9+
# Complexity
10+
- Time complexity: $$O(n)$$
11+
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
12+
13+
- Space complexity
14+
- $$O(logN)$$ (best case for balanced tree)
15+
- $$O(N)$$ (worst case for skewed tree)
16+
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
17+
(N: size of node.)
18+
# Code
19+
```
20+
func maxDepth(root *TreeNode) int {
21+
if root == nil {
22+
return 0
23+
}
24+
return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
25+
}
26+
```
27+
- - -
28+
# Intuition
29+
Implement Stack can be troublesome, but it is effective to problem that require tracking depths or levels.
30+
<!-- Describe your first thoughts on how to solve this problem. -->
31+
32+
# Approach
33+
<!-- Describe your approach to solving the problem. -->
34+
1. Maintain Element belonging to the same level in the stack.
35+
2. While Iterating through the stack, remove the current level and save the next level.
36+
- In GoLang, `range for loop` capture only first once. So We can maintain current level's easily.
37+
3. increase depth while iterationg through all elements until the end.
38+
# Complexity
39+
- Time complexity: $$O(n)$$
40+
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
41+
42+
- Space complexity
43+
- $$O(logN)$$ (best case for balanced tree)
44+
- $$O(N)$$ (worst case for skewed tree)
45+
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
46+
(N: size of node.)
47+
48+
# Code
49+
```
50+
func maxDepth(root *TreeNode) int {
51+
if root == nil {
52+
return 0
53+
}
54+
depth := 0
55+
currLevel := []*TreeNode{root}
56+
57+
for len(currLevel) != 0 {
58+
depth++
59+
for _, curr := range currLevel {
60+
if curr.Left != nil {
61+
currLevel = append(currLevel, curr.Left)
62+
}
63+
if curr.Right != nil {
64+
currLevel = append(currLevel, curr.Right)
65+
}
66+
currLevel = currLevel[1:]
67+
}
68+
}
69+
70+
return depth
71+
}
72+
```

0 commit comments

Comments
 (0)