Skip to content

Commit

Permalink
104. Maximum Depth of Binary Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
blueBlue0102 committed May 30, 2024
1 parent 8eb97ac commit fd15ca5
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package leetcode

import "github.com/blueBlue0102/LeetCode-Go/structures"

func MaximumDepthofBinaryTree(root *structures.TreeNode) int {
height := 0
if root != nil {
height++
height += max(MaximumDepthofBinaryTree(root.Left), MaximumDepthofBinaryTree(root.Right))
}
return height
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package leetcode

import (
"reflect"
"testing"

"github.com/blueBlue0102/LeetCode-Go/structures"
)

// 填入 function input type
type parameters0104 struct {
root *structures.TreeNode
}

func TestMaximumDepthofBinaryTree(t *testing.T) {
tests := []struct {
parameters0104
// 填入 function output type
ans int
}{
// 填入 test case
{
parameters0104{structures.Ints2TreeNode([]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7})},
3,
},
{
parameters0104{structures.Ints2TreeNode([]int{1, structures.NULL, 2})},
2,
},
}

for _, test := range tests {
t.Run("Test MaximumDepthofBinaryTree", func(t *testing.T) {
// 完整輸入參數
result := MaximumDepthofBinaryTree(test.parameters0104.root)
// compare 的方式需視情況調整
if !reflect.DeepEqual(result, test.ans) {
t.Errorf("MaximumDepthofBinaryTree(%+v) got %+v, want %+v", test.parameters0104, result, test.ans)
}
})
}
}
15 changes: 15 additions & 0 deletions leetcode/0104.Maximum-Depth-of-Binary-Tree/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 104. Maximum Depth of Binary Tree

<https://leetcode.com/problems/maximum-depth-of-binary-tree/>

給定一棵 Binary Tree,求樹的最大高度
(若只有 root 則高度為 1)

樹需要從 root 開始進行遍歷,但位於 root 時並無法得知右或左子樹能否達到最遠節點
所以勢必需要遍歷整棵樹

要用 pre 或 in-order 都無所謂,因為勢必就是需要遍歷每個節點

## Takeaway

- Tree Traversal

0 comments on commit fd15ca5

Please sign in to comment.