leetcode 链接:
https://leetcode.cn/problems/binary-tree-right-side-view/desc…
解题思路:
层序遍历后取每一层的最初一个值
func rightSideView(root *TreeNode) []int {res := [][]int{}
sideView := []int{}
if root == nil {return sideView}
quene := list.New()
quene.PushBack(root)
var tmpArr []int
for quene.Len() > 0 {size := quene.Len()
for i := 0; i < size; i++ {node := quene.Remove(quene.Front()).(*TreeNode)
if node.Left != nil {quene.PushBack(node.Left)
}
if node.Right != nil {quene.PushBack(node.Right)
}
tmpArr = append(tmpArr, node.Val)
}
res = append(res, tmpArr)
tmpArr = []int{}
}
for i := 0; i < len(res); i++ {sideView = append(sideView, res[i][len(res[i]) - 1])
}
return sideView
}