You are on page 1of 3

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 heres 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 }

Write a C program to delete a tree (i.e, free up its nodes) Solutions: clear(struct node* pNode) { if (pNode != NULL) { clear(pNode->left); clear(pNode->right); delete pNode; } }

Write a 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 create a copy of a linked list? Write a C program to create a copy of a linked list.

copy_linked_lists(struct node *q, struct node **s) { if(q!=NULL) { *s=malloc(sizeof(struct node)); (*s)->data=q->data; (*s)->link=NULL; copy_linked_list(q->link, &((*s)->link)); }}

How to compare two linked lists? Write a C program to compare two linked lists.

int compare_linked_lists(struct node *q, struct node *r) { static int flag; if((q==NULL ) && (r==NULL)) { flag=1; } else { if(q==NULL || r==NULL) { flag=0; } if(q->data!=r->data) { flag=0; } else { compare_linked_lists(q->link,r->link); } } return(flag); }

You might also like