Friday, 15 January 2010

java - Find the diameter of a binary tree -



java - Find the diameter of a binary tree -

i trying find diameter of binary tree (path length between 2 nodes in tree containing maximum number of nodes.) in java.

my code snippet:

public int diametre(node node, int d) { if(node==null) homecoming 0; lh=diametre(node.left, d); rh=diametre(node.right, d); if(lh+rh+1>d) d=lh+rh+1; homecoming findmax(lh, rh)+1; }

in main method:

system.out.println( bst.diametre(root,0) );

logic: post-order logic. variable 'd' refers diameter of sub-tree (in iteration.). updated , when larger value found. 'lh' refers : left sub tree's height. 'rh' refers : right sub tree's height.

but giving wrong output.

tree considered:

5 / \ / \ 1 8 \ /\ \ / \ 3 6 9

idle output: 5

but code giving 3.

can 1 figure out problem is...

public int diameter (node root) { if (root == null) homecoming 0; else homecoming 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) homecoming 0; else homecoming 1 + math.max (height (root.left), height (root.right)); }

java tree binary-tree

No comments:

Post a Comment