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%
*/

不过效率感人。。。

猜你喜欢

转载自blog.csdn.net/MIC10086/article/details/113810807