107. 二叉树的层序遍历 II

107. 二叉树的层序遍历 II

题目描述

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

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

    3
   / \
  9  20
    /  \
   15   7

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

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

题解:

这题也是两种思路:

  1. 参考 二叉树的层序遍历 ,将正常的层序遍历结果逆序即可
  2. 不使用逆序,这个稍微有点麻烦。

逆序就不写了,在 二叉树的层序遍历 基础上,将结果逆序返回就行了。

下面介绍不逆序的写法:

  • 求二叉树的高度 total_dep
  • 将结果数组 ret 设置为 total_dep 个空数组
  • 递归过程中,假设当前递归深度为 dep (从1开始),则该层节点属于 ret 中第 total_dep - dep

时间复杂度: O ( n ) O(n) O(n)

额外空间复杂度: O ( n ) O(n) O(n)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ret;
    int total_dep;
    int depth( TreeNode* root ) {
        if ( !root ) return 0;
        return 1 + max( depth( root->left ), depth( root->right) );
    }
    void dfs( TreeNode* root, int dep ) {
        if ( !root ) return;
        ret[total_dep - dep].emplace_back( root->val );
        dfs( root->left, dep + 1 );
        dfs( root->right, dep + 1 );
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        total_dep = depth( root );
        for ( int i = 0; i < total_dep; ++i ) 
            ret.emplace_back( vector<int>{} );
        dfs( root, 1 );
        return ret;
    }
};
/*
时间:0ms,击败:100.00%
内存:11.4MB,击败:71.52%
*/

当然,参考 二叉树的层序遍历 方法一 ,将新的数组插入 ret 的头部也可以:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ret;
    void dfs( TreeNode* root, int dep ) {
        if ( !root ) return;
        if ( ret.size() < dep ) 
            ret.insert( ret.begin(), vector<int>{} );
        ret[ret.size() - dep].emplace_back( root->val );
        dfs( root->left, dep + 1 );
        dfs( root->right, dep + 1 );
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        dfs( root, 1 );
        return ret;
    }
};
/*
时间:28ms,击败:7.87%
内存:12.3MB,击败:6.92%
*/

不过效率感人。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值