The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
5 / \ 3 20 / \ 7 8 Return 3 as diameter [3,5,20,8] or [3,5,20,7]
Diameter of a node is the lheight+rheight
. The problem can be solved with a similar approach involved in finding the height of the binary tree. Along with calculating the height maintain a variable to have the max diameter.
public class Solution {
int maxd = 0;
public int diameterOfBinaryTree(TreeNode root) {
height(root);
return maxd;
}
public int height(TreeNode root) {
if (root == null)
return 0;
int lh = height(root.left);
int rh = height(root.right);
int d = lh + rh;
if (d > maxd)
maxd = d;
return 1 + Math.max(lh, rh);
}
static class TreeNode {
TreeNode left;
TreeNode right;
int val;
public TreeNode(int value) {
this.val = value;
}
}
}