-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_tree.go
53 lines (51 loc) · 1.05 KB
/
basic_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
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 输出二叉树的左视图
func leftView(root *TreeNode) []int {
if root == nil {
return nil
}
var result []int
queue := []*TreeNode{root}
for len(queue) > 0 {
size := len(queue)
result = append(result, queue[0].Val) // 添加每一层的第一个元素
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return result
}
// 输出二叉树的右视图
func rightView(root *TreeNode) []int {
if root == nil {
return nil
}
var result []int
queue := []*TreeNode{root}
for len(queue) > 0 {
size := len(queue)
result = append(result, queue[size-1].Val) // 添加每一层的最后一个元素
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return result
}