107. 二叉树的层序遍历 II (力扣)

2021-01-09  本文已影响0人  历十九喵喵喵

题目:给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],

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

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

思路讲解: Arraylist 实现 的List 接口,存放类型是 一个 List集合, 利用 dfs 进行层次遍历, 最后的结果需要借助 Collections 类 的 reverse 方法,实现自 底向上的展示。
实际还是二叉树的层次遍历。

void reverse(List list):对指定 List 集合元素进行逆向排序。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 import java.util.Collections;

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        DFS(root,result,0);
        Collections.reverse(result);
        return result;
    }

    void  DFS(TreeNode root,List<List<Integer>> result,int height){
        if(root == null){
            return;
        }

        if(height >= result.size()){
            result.add(new ArrayList<>());
        }
      
        result.get(height).add(root.val);
        
        DFS(root.left, result,height + 1);
        DFS(root.right,result,height + 1);
    }

}

链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/solution/san-chong-shi-xian-tu-jie-107er-cha-shu-de-ceng-ci/

上一篇 下一篇

猜你喜欢

热点阅读