题意:

image.png

解题思路:

  1. 思路:
  2. BFS:树中每个节点仅会进队出队一次,所以时间复杂度是 O(n)
  3. 1. 先将根节点入队
  4. 2. 创建队列用来保存节点数据;
  5. 4. 对于当前队列中的所有节点,按顺序依次将儿子加入新队列,并将当前节点的值记录在答案中;
  6. 5. 继续下一层队列遍历,直到队列为空

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param TreeNode $root
  4. * @return Integer[][]
  5. */
  6. function levelOrderBottom($root) {
  7. if (!$root) return [];
  8. $res = [];
  9. $queue = [];
  10. array_push($queue, $root);
  11. while (!empty($queue)) {
  12. $list = [];
  13. foreach ($queue as $r) {
  14. array_push($list, $r->val);
  15. if ($r->left != null) array_push($queue, $r->left);
  16. if ($r->right != null) array_push($queue, $r->right);
  17. array_shift($queue);
  18. }
  19. array_unshift($res, $list);
  20. }
  21. return $res;
  22. }
  23. function levelOrderBottom1($root) {
  24. if (!$root) return [];
  25. $res = [];
  26. $queue = [];
  27. array_push($queue, $root);
  28. while (!empty($queue)) {
  29. $len = count($queue);
  30. $list = [];
  31. for ($i = 0; $i < $len; $i++) {
  32. $r = array_shift($queue);
  33. array_push($list, $r->val);
  34. if ($r->left != null) array_push($queue, $r->left);
  35. if ($r->right != null) array_push($queue, $r->right);
  36. }
  37. array_push($res, $list);
  38. }
  39. krsort($res);
  40. return $res;
  41. }
  42. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func levelOrderBottom(root *TreeNode) [][]int {
  10. res := make([][]int, 0)
  11. queue := []*TreeNode{}
  12. if root == nil {
  13. return res
  14. }
  15. queue = append(queue, root)
  16. for len(queue) > 0 {
  17. tmp := []*TreeNode{}
  18. t := make([]int, 0)
  19. for i := 0; i < len(queue); i++ {
  20. t = append(t, queue[i].Val)
  21. if queue[i].Left != nil {
  22. tmp = append(tmp, queue[i].Left)
  23. }
  24. if queue[i].Right != nil {
  25. tmp = append(tmp, queue[i].Right)
  26. }
  27. }
  28. queue = tmp
  29. res = append(res, t)
  30. }
  31. lp := 0
  32. rp := len(res) - 1
  33. for lp < rp {
  34. res[lp], res[rp] = res[rp], res[lp]
  35. lp++
  36. rp--
  37. }
  38. return res
  39. }