-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminimum_depth_of_binary_tree.go
103 lines (80 loc) · 1.97 KB
/
minimum_depth_of_binary_tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import "math"
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return 1
} else if root.Left != nil && root.Right == nil {
return minDepth(root.Left) + 1
} else if root.Left == nil && root.Right != nil {
return minDepth(root.Right) + 1
} else {
l := minDepth(root.Left)
r := minDepth(root.Right)
return int(math.Min(float64(l), float64(r))) + 1
}
}
// func minDepth(root *TreeNode) int {
// if root == nil {
// return 0
// }
// var currentDepth int = 1
// queue := NewTreeNodeQueue()
// queue.Enqueue(root)
// for !queue.IsEmpty() {
// level := queue.Size()
// for i := 0; i < level; i++ {
// node := queue.Dequeue()
// if !HasChildren(node) {
// return currentDepth
// }
// queue.EnqueueChildren(node)
// }
// currentDepth++
// }
// return currentDepth
// }
// func HasChildren(node *TreeNode) bool {
// return node.Left != nil || node.Right != nil
// }
// type TreeNodeQueue struct {
// items []*TreeNode
// }
// func NewTreeNodeQueue() *TreeNodeQueue {
// return &TreeNodeQueue{
// items: make([]*TreeNode, 0),
// }
// }
// func (q *TreeNodeQueue) EnqueueChildren(n *TreeNode) {
// if n.Left != nil {
// q.Enqueue(n.Left)
// }
// if n.Right != nil {
// q.Enqueue(n.Right)
// }
// }
// func (q *TreeNodeQueue) Enqueue(n *TreeNode) {
// q.items = append(q.items, n)
// }
// func (q *TreeNodeQueue) Dequeue() *TreeNode {
// if q.IsEmpty() {
// return nil
// }
// n := q.items[0]
// q.items = q.items[1:]
// return n
// }
// func (q *TreeNodeQueue) Size() int {
// return len(q.items)
// }
// func (q *TreeNodeQueue) IsEmpty() bool {
// return q.Size() == 0
// }