Skip to content

Instantly share code, notes, and snippets.

@montycheese
Created October 9, 2015 15:12
Show Gist options
  • Save montycheese/ee14a5d5aa993237a0f7 to your computer and use it in GitHub Desktop.
Save montycheese/ee14a5d5aa993237a0f7 to your computer and use it in GitHub Desktop.
check if a binary tree is the subtree of another. (Cannot assume that they are BST, and duplicates may be present, on either side of the original.)
public class CheckSubTre {
TreeNode<Integer> t1, t2;
//t2 might be subset of t1
public CheckSubTre(TreeNode<Integer> t1, TreeNode<Integer> t2){
this.t1 = t1;this.t2=t2;
}
public boolean check(TreeNode<Integer> t1, TreeNode<Integer> t2){
if(t1 == t2){
if(DFSMatch(t1, t2) == true) return true;
}
//look for t2's root in t1
TreeNode<Integer> subTree = find(t2.key, t1);
//t2 is not a subtree of t1....
if(subTree == null) return false;
//if both have matching configs, return true!
if(DFSMatch(subTree, t2) == true){
return true;
}
else{
check(subTree.right, t2);
check(subTree.left, t2);
}
return false;
}
public boolean DFSMatch(TreeNode<Integer> sub, TreeNode<Integer> tree){
boolean matched = true;
if(sub != tree) return false;
else if(sub == null && tree == null) return true;
else{
matched = DFSMatch(sub.left, tree.left);
matched = DFSMatch(sub.right, tree.right);
}
return matched;
}
/*
* return null if no matches found
* search a tree for a specific key value
*/
public TreeNode<Integer> find(int target, TreeNode<Integer> tree){
if(tree == null) return null;
else{
TreeNode<Integer> n;
if(tree.key == target) return tree;
else{
if(tree.key > target){
n = find(target, tree.left);
}
else if(tree.key < target){
n = find(target, tree.right);
}
else{
//case where there are duplicates, can either be right or left
//child, we have to search both
n = find(target, tree.left);
if(n != null) return n;
n = find(target, tree.right);
if(n!= null) return n;
}
return n;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment