mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0102:优化二叉树的层序遍历中199题的go方法
This commit is contained in:
@ -810,33 +810,30 @@ go:
|
|||||||
199. 二叉树的右视图
|
199. 二叉树的右视图
|
||||||
*/
|
*/
|
||||||
func rightSideView(root *TreeNode) []int {
|
func rightSideView(root *TreeNode) []int {
|
||||||
queue:=list.New()
|
if root == nil {
|
||||||
res:=[][]int{}
|
return nil
|
||||||
var finaRes []int
|
|
||||||
if root==nil{
|
|
||||||
return finaRes
|
|
||||||
}
|
}
|
||||||
|
res := make([]int, 0)
|
||||||
|
queue := list.New()
|
||||||
queue.PushBack(root)
|
queue.PushBack(root)
|
||||||
for queue.Len()>0{
|
|
||||||
length:=queue.Len()
|
for queue.Len() > 0 {
|
||||||
tmp:=[]int{}
|
length := queue.Len()
|
||||||
for i:=0;i<length;i++{
|
for i := 0; i < length; i++ {
|
||||||
node:=queue.Remove(queue.Front()).(*TreeNode)
|
node := queue.Remove(queue.Front()).(*TreeNode)
|
||||||
if node.Left!=nil{
|
if node.Left != nil {
|
||||||
queue.PushBack(node.Left)
|
queue.PushBack(node.Left)
|
||||||
}
|
}
|
||||||
if node.Right!=nil{
|
if node.Right != nil {
|
||||||
queue.PushBack(node.Right)
|
queue.PushBack(node.Right)
|
||||||
}
|
}
|
||||||
tmp=append(tmp,node.Val)
|
// 取每层的最后一个元素,添加到结果集中
|
||||||
|
if i == length-1 {
|
||||||
|
res = append(res, node.Val)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
res=append(res,tmp)
|
|
||||||
}
|
}
|
||||||
//取每一层的最后一个元素
|
return res
|
||||||
for i:=0;i<len(res);i++{
|
|
||||||
finaRes=append(finaRes,res[i][len(res[i])-1])
|
|
||||||
}
|
|
||||||
return finaRes
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user