Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 13, 2014 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislukkk/905c242ada37ac3caf95 to your computer and use it in GitHub Desktop.
Save chrislukkk/905c242ada37ac3caf95 to your computer and use it in GitHub Desktop.
Career cup 4.8 - Subtree detection
package Chapter4;
public class SubtreeFinder {
public static <T extends Comparable<T>> boolean isIdentical(TreeNode<T> r1,
TreeNode<T> r2) {
if (r1 == null && r2 == null)
return true;
if (r1 == null || r2 == null)
return false;
if (r1.key != r2.key)
return false;
return isIdentical(r1.left, r2.left) && isIdentical(r1.right, r2.right);
}
public static <T extends Comparable<T>> boolean isSubtree(TreeNode<T> n1,
TreeNode<T> n2) {
// tree with null root is subtree of all other trees
if (n2 == null)
return true;
// root is null, but target tree still has nodes
if (n1 == null)
return false;
if (isIdentical(n1, n2))
return true;
return isSubtree(n1.left, n2) || isSubtree(n1.right, n2);
}
public static void main(String[] args) {
/*
* _______7______ / \ __10__ ___2 / \ / 4 3 _8 \ / 1 11
*/
Integer[] pre = { 7, 10, 4, 3, 1, 2, 8, 11 };
Integer[] in = { 4, 10, 3, 1, 7, 11, 8, 2 };
BinaryTree<Integer> bt = BinaryTreeBuilder.buildTree(pre, in);
/*
* ___2 / _8 / 11
*/
Integer[] sub_pre = { 2, 8, 11 };
Integer[] sub_in = { 11, 8, 2 };
BinaryTree<Integer> st1 = BinaryTreeBuilder.buildTree(sub_pre, sub_in);
BinaryTree<Integer> st2 = new BinaryTree<>(new TreeNode<Integer>(8));
System.out.println("is st1 subtree of bt: "
+ isSubtree(bt.root(), st1.root()));
System.out.println("is st2 subtree of bt: "
+ isSubtree(bt.root(), st2.root()));
System.out.println("is null root subtree of bt: "
+ isSubtree(bt.root(), null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment