Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to check if a tree is a subtree of another tree?
    primarykey
    data
    text
    <p>So, I have the obvious brute-force algorithm, which goes as follows</p> <pre><code>int isSubtree (binTree *S, binTree *T) { if (S == NULL) return 0; return (isEqual (S,T) || isSubtree (S-&gt;left, T) || isSubtree (S-&gt;right, T)); } int isEqual (binTree *S, bintree *T) { if (S==NULL &amp;&amp; T==NULL) return 1; if (S==NULL || T==NULL) return 0; if (S-&gt;val == T-&gt;val) return isEqual(S-&gt;left,T-&gt;left) &amp;&amp; isEqual (S-&gt;right,T-&gt;right); else return 0; } </code></pre> <p>But this is O(n²) approach.</p> <p>I have another approach which goes as follows and is O(n) We, traverse the first tree in inorder fashion and store it in an array. Then we traverse the second tree and store it in inorder fashion. Now if the second array is a subarray of the first, we go ahead and repeat the same procudure for preorder traversal too. If both the queries result TRUE, The tree is subtree of the first tree. Otherwise, not.</p> <p>Can somebody tell me whether the following algorithm would work or not? </p> <p>And is there a more space optimized solution to this problem?</p> <p>Note: I need two arrays, since I am storing the traversals for both the arrays, is there anyway I could just do with one array? Like I would store the inorder traversal of one of the trees, and then use that array to check for the subarray condition while traversing the other tree. Or maybe no extra space but O(n) time complexity?</p> <p>Note: By sub-array, I mean that the elements should occur consecutively, i.e</p> <pre><code>{2,3,5} is a subarray of {1,2,3,5} but not a subarray of {1,2,3,4,5} </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload