LeetCode 366 (LintCode 650) Find Leaves of Binary Tree

54 篇文章 2 订阅
18 篇文章 0 订阅

思路

类似与求树的高度(分治)。在每次求得当前节点的高度后,使用hashmap将结果保存下来(key=高度,value=一个list,存的是高度=key的所有节点的value)。由于使用分治法递归求树的高度的过程中,已经将每个节点的高度都求了一遍,所以在每次求得高度后将高度与节点值直接存到hashmap中,就不用对每一个节点进行一遍dfs了,保证时间复杂度为线性。

代码

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @return: collect and remove all leaves
     */
    public List<List<Integer>> findLeaves(TreeNode root) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        Map<Integer, List<Integer>> hash = new HashMap<>();
        
        int maxHeight = dfs(root, hash);
        for(int i = 1; i <= maxHeight; i++) {
            res.add(hash.get(i));
        }
        
        return res;
    }
    
    public int dfs(TreeNode root, Map<Integer, List<Integer>> hash) {
        if(root == null) return 0;
        // divide (left + right)
        int height = Math.max(dfs(root.left, hash), dfs(root.right, hash)) + 1;
        
        hash.putIfAbsent(height, new ArrayList<>());
        hash.get(height).add(root.val);
        
        return height;
    }
}

复杂度

时间复杂度O(n): 每个节点访问有且仅有一次
空间复杂度O(logn):递归栈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值