Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking subtrees using preorder and inorder strings

A book I'm reading claims that one way to check whether a binary tree B is a subtree of a binary tree A is to build the inorder and preorder strings (strings that represent the inorder and preorder traversal of each tree) of both trees, and check whether inorder_B is a substring of inorder_A and preorder_B is a substring of preorder_A. Note that it claims that you have to check substring match on both the inorder and preorder strings.

Is it really necessary to check for a substring match on both the inorder and preorder strings? Wouldn't it suffice to check either? Could someone provide an example to prove me wrong (i.e. prove the claim in the book right)? I couldn't come up with an example where two trees were unequal but the preorder or inorder strings match.

like image 857
fo_x86 Avatar asked Jan 11 '13 22:01

fo_x86


2 Answers

Consider the two two node trees with A and B as nodes. Tree one has B as root and A as left child. Tree two has A as root and B as right child. The inorder traversals match but the trees differ.

like image 125
DrC Avatar answered Sep 27 '22 17:09

DrC


I think you need both if the tree is not a binary search tree but a plain binary tree. Any set of nodes can be a preorder notation. Suppose there is a binary tree a,b,c,d,e,f,g,h and your subtree is cdef. You can create another tree with subtree cde and another subtree fg. There is no way to know the difference.

If it is a binary search tree however you needn't have the inorder.

Incidentally here's an amusing algorithmic problem: given a preorder notation find the number of binary trees that satisfy it.

like image 39
user1952500 Avatar answered Sep 27 '22 17:09

user1952500