-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsolution.go
58 lines (53 loc) · 975 Bytes
/
solution.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
package leetcode
/*
* @lc app=leetcode.cn id=199 lang=golang
*
* [199] 二叉树的右视图
*/
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func rightSideView(root *TreeNode) []int {
res := []int{}
if root == nil {
return res
}
queue := []*TreeNode{root}
res = []int{root.Val}
for len(queue) > 0 {
l := len(queue)
flag := 0
for i := 0; i < l; i++ {
node := queue[i]
if node.Right != nil {
if flag == 0 {
flag = node.Right.Val
}
queue = append(queue, node.Right)
}
if node.Left != nil {
if flag == 0 {
flag = node.Left.Val
}
queue = append(queue, node.Left)
}
}
if flag != 0 {
res = append(res, flag)
}
queue = queue[l:]
}
return res
}
// @lc code=end