Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the diameter of a binary tree

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...

like image 853
loknath Avatar asked Feb 19 '13 09:02

loknath


People also ask

What is a diameter of tree?

The diameter of a tree is the number of nodes on the longest path between two leaves in the tree.

What is diameter of tree in DS?

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.

What is the diameter of a tree Computer Science?

The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.

How do you find the diameter of a tree?

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.


1 Answers

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));
}
like image 91
Mikhail Vladimirov Avatar answered Oct 14 '22 23:10

Mikhail Vladimirov