leetCode打卡—— 107 Binary Tree Level Order Traversal II

390 阅读1分钟

题目

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example: Given binary tree [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

return its bottom-up level order traversal as:

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

思路

这道题我是用深度优先做出来的,然后看了一下别人的广度优先解法。

dfs

  1. 使用递归的思想,每一个节点记录自己的当前层数(root算0层),如果层数 + 1大于当前结果已有的层数,则结果push在头部插入一个新的空层。
  2. 第一步保证了当前节点所在层数存在,因为是倒序的显示,比如第0层的节点,在结果的第res.length - 1 - 0层,第1层的节点,在结果的res.length - 1 - 1层。
var levelOrderBottom = function(root) {
    return run(root, 0, []);
};
var run = function(node, nowFloor, res) {
    if (node) {
        if (res.length < nowFloor + 1) {
            res.unshift([]);
        }
        const reverseNowFloor = res.length - nowFloor - 1;
        
        res[reverseNowFloor].push(node.val);

        run(node.left, nowFloor + 1, res);
        run(node.right, nowFloor + 1, res);
    }
    return res;
}

bfs

  1. 用队列的形式,先处理完一层的结果,然后从结果中插入该层,即可完成倒序显示
var levelOrderBottom = function(root) {
    return run2(root);
};
var run2 = function(node) {
    var queue = [node];

    var res = [];

    while (queue.length) {
        const nowQueueLen = queue.length;
        var floor = [];
        for (let i = 0; i < nowQueueLen; i++) {
            var nowNode = queue.shift();
            
            floor.push(nowNode.val);

            if (nowNode.left)
                queue.push(nowNode.left);
            if (nowNode.right)
                queue.push(nowNode.right);
        }
        res.unshift(floor);
    }
    return res;
}