1. 题目描述

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

返回其自底向上的层次遍历为:

  1. [
  2. [15,7],
  3. [9,20],
  4. [3]
  5. ]

2. 实现思路

对于这道题目,对二叉树进行层序遍历,最直接的方法就是使用BFS(广度优先遍历)。

首先创建一个队列,将当前你的节点放进去,队列中的节点始终是当前层的节点。按顺序出列,加入结果中,并将当前节点的子节点加入到队列中。

重复上述步骤,直到队列为空,就遍历完了整个二叉树。

该方法的时间复杂度为O(n)

3. 代码实现

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {number[][]}
  11. */
  12. var levelOrderBottom = function(root) {
  13. if(!root) {
  14. return []
  15. }
  16. const queue = []
  17. queue.push(root)
  18. const res = [] // 用来储存最后的结果
  19. while(queue.length){
  20. const subRes = [] // 用来储存每一层的节点值
  21. const levelSize = queue.length
  22. for(let i = 0; i < levelSize; i++){
  23. const cur = queue.shift()
  24. subRes.push(cur.val)
  25. if(cur.left){
  26. queue.push(cur.left)
  27. }
  28. if(cur.right){
  29. queue.push(cur.right)
  30. }
  31. }
  32. res.unshift(subRes)
  33. }
  34. return res
  35. };

4. 提交结果

107. 二叉树的层次遍历 II - 图1