【路飞】算法与数据结构-二叉树的层序遍历 II

105 阅读1分钟

LeetCode:地址

题目要求

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

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

   3
   / \
  9  20
    /  \
   15   7

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

[
  [15,7],
  [9,20],
  [3]
]
思路

层序遍历最后的结果数组,反转即可。

代码
const levelOrderBottom = root => {
    if (!root) return [];
    // 根节点入队
    const q = [root];
    // 返回值
    const res = [];
    while (q.length) {
        // 当前层的数量
        let len = q.length;
        // res中放入一个装当前层的空数组
        res.push([]);
        while (len--) {
            // 从队列中,将当前层的元素推入res的尾巴数组中
            const n = q.shift();
            res[res.length - 1].push(n.val);
            n.left && q.push(n.left);
            n.right && q.push(n.right);
        }
    }
    return res.reverse();
};