美文网首页
107. 二叉树的层序遍历 II (力扣)

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

作者: 历十九喵喵喵 | 来源:发表于2021-01-09 21:30 被阅读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/

    相关文章

      网友评论

          本文标题:107. 二叉树的层序遍历 II (力扣)

          本文链接:https://www.haomeiwen.com/subject/sifhaktx.html