is Subtree

/*** 4.8
You have two very large binary trees: T1, with millions of nodes, and T2, with
 hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T2 such that the subtree
of n is identical to T2. That is, if you cut off the tree at node n, the two
trees would be identical.
IDEA: bottom-up find the root of t2 and then top-down compare.
***/

#include<iostream>

using namespace std;

struct node {
       int val;
       node *left;
       node *right;
};

bool match(node *root1, node *root2) {

       if(root1 == nullptr && root2 == nullptr) return true;
       if(root1 == nullptr || root2 == nullptr) return false;

       if(root1->val != root2->val) return false;
       if(!match(root1->left, root2->left)) return false;
       if(!match(root1->right, root1->right)) return false;
       return true;
}

bool findT2root(node *T1root, node *T2root) {

       if(T1root == nullptr) return false;

       if(T1root->val == T2root->val) {
              node *T2 = T2root;
              if(match(T1root, T2)) return true;
       }

       if(findT2root(T1root->left, T2root)) return true;
       if(findT2root(T1root->right, T2root)) return true;

       return false;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs