Saturday, March 24, 2012
Write anagram generator?
Lets use erlang to solve it
-module(anagram).
-compile([export_all]).
anagram([ ]) -> [ [ ]];
anagram(L) -> [[H|T] || H <- L, T <- anagram(L -- [H])].
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)).
-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)).
Find the diameter of a binary tree
![]() |
| Diameter of a binary tree |
Diameter of a tree is the maximum distance between any of its two nodes. In the above diagram the nodes used to calculate the diameter of tree is highlighted in red color.
Let us write a c program to find the width of the binary tree. We shall use recursion to solve this algorithm.
Lets us define a function called Max which returns a max of two variables.
int max(int a, int b)
{
return (a > b ? a : b);
}
{
struct BTreeNode *left;
struct BTreeNode *right;
int data;
};
int TreeWidth(struct BTreeNode *root, int *pWidth)
{
int left, right;
//If the root is null, return the height as 0
if(!root)
return 0;
//Get the height of the left sub tree
left = TreeWidth(root->left,pWidth);
//Get the height of the right sub tree
right = TreeWidth(root->right,pWidth);
/*Compare the previous width with the sum of left and right sub tree and store the max of the two values as the new width*/
*
pWidth = max(*
pWidth , (left + right));
//add one to the height of the sub tree and return as the new height
return max(left, right) + 1;
}












