题目:
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
解法:
二叉树的层序遍历
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
ans := make([]int, 0)
list := make([]*TreeNode, 0)
head := root
if head != nil {
list = append(list, head)
}
for len(list) != 0 {
l := len(list) - 1
ans = append(ans, list[l].Val)
for i := 0; i <= l; i ++ {
if list[i].Left != nil {
list = append(list, list[i].Left)
}
if list[i].Right != nil {
list = append(list, list[i].Right)
}
}
list = list[l + 1:]
}
return ans
}