Created
July 17, 2014 21:11
-
-
Save jyhjuzi/2c5192865cd2fefdaaf6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Q4_8{ | |
public static void main(String[] args){ | |
int[] array = { 1,2,3,4,5,6,7,8 }; | |
int[] subArray ={5,6,7,8}; | |
TreeNode<Integer> root1 = new Q4_3().arrayToBST(array, 0, 7); | |
TreeNode<Integer> root2 = new Q4_3().arrayToBST(subArray, 0, 3); | |
/*TreeNode<Integer> root2 = new TreeNode<Integer>(7,null,new TreeNode<Integer>(8));*/ | |
System.out.println(isSubTree(root1,root2)); | |
} | |
public static boolean isSubTree(TreeNode<Integer> root1, TreeNode<Integer> root2){ | |
if(root1==null) | |
return false; | |
if(root2==null) | |
return true; | |
TreeNode<Integer> cur = root1; | |
if(cur.value == root2.value) | |
if(match(cur,root2)) | |
return true; | |
if(isSubTree(root1.left,root2)) | |
return true; | |
if(isSubTree(root1.right,root2)) | |
return true; | |
return false; | |
} | |
public static boolean match(TreeNode<Integer> node1, TreeNode<Integer> node2){ | |
if(node1 == null && node2 ==null) | |
return true; | |
if(node1==null || node2== null) | |
return false; | |
if(node1.value == node2.value) | |
return match(node1.left,node2.left) && match(node1.right, node2.right); | |
else return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment