Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created February 6, 2013 19:05
Show Gist options
  • Save charlespunk/4724932 to your computer and use it in GitHub Desktop.
Save charlespunk/4724932 to your computer and use it in GitHub Desktop.
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 if T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut of the tree at node n, the two trees would be identical.
public static boolean containsTree(Node root, Node subtree){
if(root == null) return false;
if(subtree == null) return true;
if(root.value == subTree.value && ckeckTree(root, subtree)) return true;
return (containsTree(root.left, subtree) || containsTree(root.right, subtree));
}
public static boolean ckeckTree(Node root, Node subtree){
if(root == null && subtree == null) return true;
else if(root == null || subtree == null) return false;
return (root.value == subtree.value && ckeckTree(root.left, subtree.left) && ckeckTree(root.right, subtree.right));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment