I am trying to find the diameter of a binary tree (Path length between any two nodes in the tree containing maximum number of nodes.) in java.
my code snippet:
public int diametre(Node node, int d)
{
if(node==null)
return 0;
lh=diametre(node.left, d);
rh=diametre(node.right, d);
if(lh+rh+1>d)
d=lh+rh+1;
return findMax(lh, rh)+1;
}
In main method:
System.out.println( bst.diametre(root,0) );
Logic: Its actually post-order logic. variable 'd' refers to the diameter of the sub-tree (In that iteration.). It will be updated as and when some larger value found. 'lh' refers to : Left sub tree's height. 'rh' refers to : right sub tree's height.
But its giving wrong output.
Tree considered:
5
/ \
/ \
1 8
\ /\
\ / \
3 6 9
Idle output: 5
But this code is giving 3.
Can some one figure out where the problem is...
The diameter of a tree is the number of nodes on the longest path between two leaves in the tree.
Tree Diameter – Diameter of a Binary Tree Diameter: The diameter of a tree is the length of the longest path between any 2 nodes of a tree. The length of a path is counted as the number of edges lying on that path.
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.
To find the diameter of a tree on a slope: Measure the circumference of the tree at breast height (usually, 1.35 m from the ground) on its uphill side. Divide the tree circumference by π (= 3.14) to estimate your tree's diameter at breast height (DBH) on a slope.
public int diameter (Node root)
{
if (root == null) return 0;
else return Math.max (
diameter (root.left),
Math.max (
diameter (root.right),
height (root.left) + height (root.right) + 1));
}
public int height (Node root)
{
if (root == null) return 0;
else return 1 + Math.max (height (root.left), height (root.right));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With