Be the first user to complete this post

  • 0
Add to List
Medium

46. Check if One Binary Tree is a Subtree of Another

Objective: Given two binary trees, check if one binary tree is a subtree of another

Example:

Tree is subtree of another tree example

Approach:

We know that identifying any binary tree can be represented as the combination of either inorder and preorder traversal OR inorder and postorder traversal OR inorder and Level order traversal.

  • Say our trees are A and B.
  • Do the inorder traversal of treeA and store it in a String say inorderA.
  • Do the inorder traversal of treeB and store it in a String say inorderB.
  • Do the postorder traversal of treeA and store it in a String say postorderA.
  • Do the postorder traversal of treeB and store it in a String say postorderB.
  • Check if inorderA contains inorderB AND postorderA contains postorderB then it means treeB is a subtree of treeA.

Time Complexity : O(n)

Tree is subtree of another tree
 

Tree A : 3 2 1 5 4 6
Tree B : 5 4 6
true