题目

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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;
    }
}