Wednesday 14 September 2011

Diameter of a binary tree


Given a binary tree you need to find the diameter of the binary tree. Diameter is defined as the maximum distance possible between any two nodes in the binary tree (It is implicit that the nodes will be the leaf nodes of the tree).




int LintkedIntTree::diameter(BinaryTreeIntNode* node) { if(node == NULL) { return 0; } int hl=heightRec(node->left); int hr=heightRec(node->right); int ld=diameter(node->left); int lr=diameter(node->right); return (ld>lr?ld:lr)>(hl+hr+1)?(ld>lr?ld:lr):(hl+hr+1); }

No comments:

Post a Comment