LeetCode 热题100-85-二叉树直径

核心思想:hashmap+后续遍历二叉树
思路:

class Solution {
    int count = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        HashMap<TreeNode, Integer> map = new HashMap<>();
        hxbl(root, map);
        return count;
    }

    public void hxbl(TreeNode root, HashMap<TreeNode, Integer> map){
        if(root == null){
            return;
        }
        hxbl(root.left, map);
        hxbl(root.right, map);
        int tem = 0;
        if(root.left == null && root.right == null){
            map.put(root, 1);
            tem = 0;
        }else{
            map.put(root, Math.max(map.getOrDefault(root.left, 0), map.getOrDefault(root.right, 0)) + 1);
            tem = map.getOrDefault(root.left, 0) + map.getOrDefault(root.right, 0);
        }
        if(tem > count){
            count = tem;
        }
    }

}

你可能感兴趣的:(Leetcode热题100,leetcode,链表,数据结构)