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