Find Leaves of Binary Tree

225 篇文章 0 订阅

Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:
Given binary tree 

          1
         / \
        2   3
       / \     
      4   5    

Returns [4, 5, 3], [2], [1].

Explanation:

1. Removing the leaves [4, 5, 3] would result in this tree:

          1
         / 
        2          

2. Now removing the leaf [2] would result in this tree:

          1          

3. Now removing the leaf [1] would result in the empty tree:

          []         

Returns [4, 5, 3], [2], [1].


这道题一开始看到层遍历,想拿hashmap保存层跟list的关系,看了其他的网上的思路后突然明白不需要这么麻烦。因为在实现的时候是通过递归实现的,所以一定会从小的号开始递增,也就是说计算当前节点的结果之前,一定会计算它的孩子,而它的孩子的高度一定比他低,所以在结果里一定有比他深度低的元素,而且它不会比子节点超过1层。


所以这个算法的本质就是按层添加,属于哪一层的加到哪一层。


代码:

public List<List<Integer>> findLeaves(TreeNode root) {
        //找到它的深度,然后把值存到hashmap对应key当中,就可以了
        //HashMap<Integer, List<Integer>>
        List<List<Integer>> result = new ArrayList<>();
        int level = getLeaf(root, result);
        return result;
    }

    private int getLeaf(TreeNode node, List<List<Integer>> result){
        if(node == null) return -1;
        int height = 1 + Math.max(getLeaf(node.left, result), getLeaf(node.right, result));
        if(height>=result.size()){
            result.add(new ArrayList<>());
        }
        result.get(height).add(node.val);
        return height;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值