Showing posts from August, 2015

Determining if Two Trees are Identical - C Programming Tutorial

In this c programming tutorial we are going to see how we can compare two trees to check whether they are identical or not. Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Below is the simple Algorithm to compare two trees : sameTree(tree1, tree2)1. If both trees are empty then return 12. Else If both trees are non -empty Check data of the root nodes (tree1->data == tree2->data) Check left subtrees recursively i.e., call sameTree( tree1->left_subtree, tree2->left_subtree) Check right subtrees recursively i.e., call sameTree( tree1->right_subtree, tree2->right_subtree) If a,b and c are true then return 1.3. Else return 0 (one is empty and other is not) Time Complexity : Complexity of the identicalTree() will be according to the tree with lesser number of nodes