题目

Solution

The longest path through that node equals:

left subtree depth + right subtree depth.

the longest path must pass through some node as a highest point.

Java

class Solution {

    private int ans = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return ans;
    }

    private int depth(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int left = depth(node.left);
        int right = depth(node.right);

        ans = Math.max(ans, left + right);
        return Math.max(left, right) + 1;
    }
}