Showing posts with label binary search. Show all posts
Showing posts with label binary search. Show all posts

C program to find the depth or height of a tree?

Solution:
  
tree_height(mynode *p) {
   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); }



The degree of the leaf is zero. The degree of a tree is the max of its element degrees. A binary tree of height n, h > 0, has at least h and at most (2^h -1) elements in it. The height of a binary tree that contains n, n>0, elements is at most n and atleast log(n+1) to the base 2.

Log(n+1) to the base 2 = h

n = (2^h - 1)

How to check if a binary tree is balanced?

Solution:


A tree is considered balanced when the difference between the min depth and max depth does not exceed 1.
Recursive algorithms always work well on trees, so here’s some code.
int min_depth( Node * root ) {
    if( !root ) {
        return 0;
    }
    return 1 + min( min_depth( root->left ),
                    min_depth( root->right ));
}

int max_depth( Node * root ) {
    if( !root ) {
        return 0;
    }
    return 1 + max( max_depth( root->left ),
                            max_depth( root->right ));
} 

bool is_balanced( Node * root ) {
    return ( max_depth( root ) - min_depth( root ) ) <= 1

difference between linear search and binary search

Answer:The main difference b/n Linear search and Binary search are given below:
Linear search: Linear search starts to search first records of the list and going on until it finds the matched record or to the end of list.In Linear Linked list their is no need to sort the file in a particular order.

Binary search: Their is three steps you have to follow when you using Binary search.

1.It starts with to select the middle item of the list.When the key item is less than the selected item than Binary search take the item between the current item and the start element of the list.Otherwise, if key item is greater than the selected item than Binary search take the item between the current item and the last element of the list.Benefit of its is that after taking one comparison it delete the half list.
2.If key item is less than the current item than we only take half list who is less than the key.Otherwise,If key item is greater than the current item than we only take half list who is greater than the key.And start in again.
3.We repeat step2 till we not reached our desired key.