543. Diameter of Binary Tree
1
/ \
2 3
/ \
4 5 class Solution {
int ans;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
di(root);
return ans;
}
public int di(TreeNode root) {
if (root == null) return 0;
int left = di(root.left), right = di(root.right);
ans = Math.max(ans, left + right);
return Math.max(left, right) + 1;
}
}Last updated