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.
sameTree(tree1, tree2) 1. If both trees are empty then return 1. 2. Else If both trees are non -empty (a) Check data of the root nodes (tree1->data == tree2->data) (b) Check left subtrees recursively i.e., call sameTree( tree1->left_subtree, tree2->left_subtree) (c) Check right subtrees recursively i.e., call sameTree( tree1->right_subtree, tree2->right_subtree) (d) If a,b and c are true then return 1. 3 Else return 0 (one is empty and other is not)
Both trees are identical
Complexity of the identicalTree() will be according to the tree with lesser number of nodes. Let number of nodes in two trees be m and n then complexity of sameTree() is O(m) where m < n.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Iterative function to check if two trees are identical
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Generic Trees(N-array Trees)
- Find largest subtree having identical left and right subtrees
- How to determine if a binary tree is height-balanced?
- Determine the count of Leaf nodes in an N-ary tree
- Write a function to get the intersection point of two Linked Lists
- Print Common Nodes in Two Binary Search Trees
- Check if leaf traversal of two Binary Trees is same?
- Check if two trees are Mirror
- Find first non matching leaves in two binary trees
- Iterative method to check if two trees are mirror of each other
- Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
- Check if all levels of two trees are anagrams or not
- Check if two trees are Mirror | Set 2
- Check if two trees are mirror of each other using level order traversal
- Check if two trees have same structure
- Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal
- Construct a Maximum Binary Tree from two given Binary Trees
- Iterative Approach to check if two Binary Trees are Isomorphic or not