Wednesday, 28 June 2017

Trees

get the height of the tree 

int tree_height(mynode *p)
{
 int h1,h2;
 if(p==NULL)return(0);
 if(p->left){h1=tree_height(p->left);}
 if(p=>right){h2=tree_height(p->right);}
 return(max(h1,h2)+1);
} 
determine the number of elements (or size) in a tree.  


int tree_size(struct node* node)
{
 if (node==NULL)
 {
 return(0);
 }
 else
 {
 return(tree_size(node->left) + tree_size(node->right) + 1);
 }
} 
 
 
mininum value in a binary search tree
 

int minValue(struct node* node)
{
 struct node* current = node;
 while (current->left != NULL)
 {
 current = current->left;
 }

 return(current->data);
}
 
 
maximum depth in a tree

int maxDepth(struct node* node)
{
 if (node==NULL)
 {
 return(0);
 }
 else
 {
 int leftDepth = maxDepth(node->left);
 int rightDepth = maxDepth(node->right);
 if (leftDepth > rightDepth)
   return(leftDepth+1);
 else 
   return(rightDepth+1);
 }
} 
create a mirror copy of a tree (left nodes become right and right nodes
become left)! 

mynode *copy(mynode *root)
{
 mynode *temp;

 if(root==NULL)return(NULL);

 temp = (mynode *) malloc(sizeof(mynode));
 temp->value = root->value;
 temp->left = copy(root->right);
 temp->right = copy(root->left);
 return(temp);
} 
 
count the number of leaves in a tree 
void count_leaf(mynode *root)
{
 if(root!=NULL)
 {
 count_leaf(root->left);

 if(root->left == NULL && root->right==NULL)
 {
 // This is a leaf!
 count++;
 }
 count_leaf(root->right);
 }
} 
 convert a tree into an array
The array representation would be
a[1] a[2] a[3] a[4] a[5] a[6] a[7]
 A     B    C    D    E   F    G 
we have a tree like this
    A
  B    C
 D E  F G
If i > 1, i/2 is the parent
If 2*i > n, then there is no left child, else 2*i is the left child.
If (2*i + 1) > n, then there is no right child, else (2*i + 1) 
               is the right child.   

 
   

No comments:

Post a Comment