当前位置:   article > 正文

Golang | Leetcode Golang题解之第199题二叉树的右视图

Golang | Leetcode Golang题解之第199题二叉树的右视图

题目:

题解:

  1. /**
  2. 102. 二叉树的递归遍历
  3. */
  4. func levelOrder(root *TreeNode) [][]int {
  5. arr := [][]int{}
  6. depth := 0
  7. var order func(root *TreeNode, depth int)
  8. order = func(root *TreeNode, depth int) {
  9. if root == nil {
  10. return
  11. }
  12. if len(arr) == depth {
  13. arr = append(arr, []int{})
  14. }
  15. arr[depth] = append(arr[depth], root.Val)
  16. order(root.Left, depth+1)
  17. order(root.Right, depth+1)
  18. }
  19. order(root, depth)
  20. return arr
  21. }
  22. /**
  23. 102. 二叉树的层序遍历
  24. */
  25. func levelOrder(root *TreeNode) [][]int {
  26. res:=[][]int{}
  27. if root==nil{//防止为空
  28. return res
  29. }
  30. queue:=list.New()
  31. queue.PushBack(root)
  32. var tmpArr []int
  33. for queue.Len()>0 {
  34. length:=queue.Len()//保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
  35. for i:=0;i<length;i++{
  36. node:=queue.Remove(queue.Front()).(*TreeNode)//出队列
  37. if node.Left!=nil{
  38. queue.PushBack(node.Left)
  39. }
  40. if node.Right!=nil{
  41. queue.PushBack(node.Right)
  42. }
  43. tmpArr=append(tmpArr,node.Val)//将值加入本层切片中
  44. }
  45. res=append(res,tmpArr)//放入结果集
  46. tmpArr=[]int{}//清空层的数据
  47. }
  48. return res
  49. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/773353
推荐阅读
相关标签
  

闽ICP备14008679号