Leetcode 543. Diameter of Binary Tree
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private static int longestPath = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return longestPath;
}
private int maxDepth(TreeNode node) {
if (node == null) return 0;
int left = maxDepth(node.left);
int right = maxDepth(node.right);
// Compare case 3 with global max
longestPath = Math.max(longestPath, left + right);
return Math.max(left, right) + 1;
}
}