首页 > 其他 > 详细

107. 二叉树的层次遍历 II-简单

时间:2020-07-12 21:34:49      阅读:61      评论:0      收藏:0      [点我收藏+]

问题描述

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

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

3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 /*
dfs遍历二叉树,从左至右。每个元素都有个deep(深度),只需将root.val放入result.get(deep)数组中即可。
时间复杂度O(n),击败98%用户。
 */
class Solution {
    public static List<List<Integer>> result;
    public static void dfs(TreeNode root,int deep){
        if(root.left == null && root.right == null)return;
        if(root.left!=null){
            if(deep+1 > (result.size())-1)result.add(new ArrayList<Integer>());
            result.get(deep+1).add(root.left.val);
            dfs(root.left,deep+1);
        }
        if(root.right!=null){
            if(deep+1 > (result.size())-1)result.add(new ArrayList<Integer>());
            result.get(deep+1).add(root.right.val);
            dfs(root.right,deep+1);
        }
    }
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        result = new ArrayList<List<Integer>>();
        if(root == null)return result;
        result.add(new ArrayList<Integer>());
        result.get(0).add(root.val);
        dfs(root,0);
        Collections.reverse(result);
        return result;
    }
}

 

107. 二叉树的层次遍历 II-简单

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13289526.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!