543 Diameter of Binary Tree
543. Diameter of Binary Tree
1. Question
1
/ \
2 3
/ \
4 52. Implementation
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
int[] max = new int[1];
getMaxDepth(root, max);
return max[0];
}
public int getMaxDepth(TreeNode node, int[] max) {
if (node == null) {
return 0;
}
int maxLeftDepth = getMaxDepth(node.left, max);
int maxRightDepth = getMaxDepth(node.right, max);
max[0] = Math.max(max[0], maxLeftDepth + maxRightDepth);
return 1 + Math.max(maxLeftDepth, maxRightDepth);
}
}3. Time & Space Complexity
Last updated