Tuesday, March 6, 2012

Find the height of a binary tree


Lets us write an algorithm to find the height of a binary tree in c

//Define Binary tree node
struct BTreeNode 
{
   struct BTreeNode *left;

   struct BTreeNode *right;

   int data;
} ;



//Function to find the maximum of two variables
int max(int a , int b)
{
    return (a > b ? a : b);
}

//Function to find the height of a binary tree
int height(struct BTreeNode *root)
{
  
   if(!root)
      return 0;
   return max(root->left, root->right) + 1;
}
  

Lets write this algorithm in Erlang

-module(binaryTree).
-export([height/1]).

 
%%define a record for binary tree node


-record(node, {val,left=nil,right=nil}).

maxval(A,B) when A > B -> A;
maxval(A,B) when A =< B -> B.

height(nil) -> 0;
height(Node) -> 1 + maxval(height(Node#node.left) , height(Node#node.right)).



0 comments:

Post a Comment