lc-543


/**
Given the root of a binary tree, return the length of the diameter of the tree. 


 The diameter of a binary tree is the length of the longest path between any 
two nodes in a tree. This path may or may not pass through the root. 

 The length of a path between two nodes is represented by the number of edges 
between them. 

 
 Example 1: 

 
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
 

 Example 2: 

 
Input: root = [1,2]
Output: 1
 

 
 Constraints: 

 
 The number of nodes in the tree is in the range [1, 10⁴]. 
 -100 <= Node.val <= 100 
 
 Related Topics树 | 深度优先搜索 | 二叉树 

 👍 1179, 👎 0 

*/
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Map<TreeNode, Integer> rootLenMap = new HashMap<>();
        Map<TreeNode, Integer> maxLenMap = new HashMap<>();


        return getMaxLen(maxLenMap, rootLenMap, root) - 1;
    }

    private int getRootLen(Map<TreeNode, Integer> rootLenMap, TreeNode root) {
        int len = 0;
        if (root != null) {
            int leftLen = getRootLen(rootLenMap, root.left);
            int rightLen = getRootLen(rootLenMap, root.right);

            len = Math.max(leftLen, rightLen) + 1;
        }

        rootLenMap.put(root, len);
        return len;
    }

    private int getMaxLen(Map<TreeNode, Integer> maxLenMap, Map<TreeNode, Integer> rootLenMap, TreeNode root) {
        int len = 0;
        if (root != null) {
            int leftLen = getRootLen(rootLenMap, root.left);
            int rightLen = getRootLen(rootLenMap, root.right);

            int leftMax = getMaxLen(maxLenMap, rootLenMap, root.left);
            int rightMax = getMaxLen(maxLenMap, rootLenMap, root.right);

            len = Math.max(leftLen + rightLen + 1, Math.max(leftMax, rightMax));
        }

        maxLenMap.put(root, len);
        return len;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !