Skip to content

Commit 18d02eb

Browse files
committed
Maximum Depth of Binary Tree
1 parent 93f02e8 commit 18d02eb

File tree

4 files changed

+75
-2
lines changed

4 files changed

+75
-2
lines changed
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
# Problem: 135. Binary Tree Postorder Traversal
1+
# Problem: 102. Binary Tree Level Order Traversal
22

3-
Post-order traversal is to traverse the left subtree first. Then traverse the right subtree. Finally, visit the root.
3+
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Problem: 104. Maximum Depth of Binary Tree
2+
3+
Given a binary tree, find its maximum depth.
4+
5+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package maximumdepthofbunarytree
2+
3+
// TreeNode data structure
4+
type TreeNode struct {
5+
Val int
6+
Left *TreeNode
7+
Right *TreeNode
8+
}
9+
10+
func maxDepth(root *TreeNode) int {
11+
if root == nil {
12+
return 0
13+
}
14+
left := maxDepth(root.Left)
15+
right := maxDepth(root.Right)
16+
ret := max(left, right) + 1
17+
return ret
18+
}
19+
20+
func max(a, b int) int {
21+
if a < b {
22+
return b
23+
}
24+
return a
25+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package maximumdepthofbunarytree
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestMaxDepth(t *testing.T) {
9+
testCases := []struct {
10+
Input *TreeNode
11+
Output int
12+
}{
13+
{
14+
Input: &TreeNode{
15+
Val: 3,
16+
Left: &TreeNode{
17+
Val: 9,
18+
},
19+
Right: &TreeNode{
20+
Val: 20,
21+
Left: &TreeNode{
22+
Val: 15,
23+
},
24+
Right: &TreeNode{
25+
Val: 7,
26+
},
27+
},
28+
},
29+
Output: 3,
30+
},
31+
{
32+
Input: nil,
33+
Output: 0,
34+
},
35+
}
36+
37+
for _, test := range testCases {
38+
out := maxDepth(test.Input)
39+
if !reflect.DeepEqual(test.Output, out) {
40+
t.Errorf("expected to get %#v, but got %#v", test.Output, out)
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)