码迷,mamicode.com
首页 > 其他好文 > 详细

直径问题 Diameter Problems

时间:2019-11-03 22:05:23      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:har   binary   csharp   set   hashmap   最大   计算   new   idt   

2019-11-03 21:37:59

一、Diameter of Binary Tree

问题描述:

技术图片

 

 

问题求解:

解法一、第一反应是树上动归,每个节点保存一下左右的最大深度,最后以每个节点作为中枢计算最大的长度即可。

    public int diameterOfBinaryTree(TreeNode root) {
        Map<TreeNode, int[]> map = new HashMap<>();
        dfs(root, map);
        int res = 0;
        for (TreeNode key : map.keySet()) {
            res = Math.max(res, map.get(key)[0] + map.get(key)[1]);
        }
        return res;
    }
    
    private int[] dfs(TreeNode root, Map<TreeNode, int[]> map) {
        if (root == null) return new int[]{-1, -1};
        int[] l = dfs(root.left, map);
        int[] r = dfs(root.right, map);
        map.put(root, new int[]{Math.max(l[0], l[1]) + 1, Math.max(r[0], r[1]) + 1});
        return map.get(root);
    }

解法二、不求直径,而是转求每个节点的最大深度,遍历的时候可以顺便得到直径。

    public int diameterOfBinaryTree(TreeNode root) {
        int[] res = new int[1];
        helper(root, res);
        return res[0];
    }
    
    private int helper(TreeNode root, int[] res) {
        if (root == null) return 0;
        int l = helper(root.left, res);
        int r = helper(root.right, res);
        res[0] = Math.max(res[0], l + r);
        return Math.max(l, r) + 1;
    }

 

直径问题 Diameter Problems

标签:har   binary   csharp   set   hashmap   最大   计算   new   idt   

原文地址:https://www.cnblogs.com/hyserendipity/p/11789309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!