题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
1 package newcoder; 2 3 /* 4 * 题目描述 5 * 输入两棵二叉树A,B,判断B是不是A的子结构。 6 * (ps:我们约定空树不是任意一个树的子结构) 7 */ 8 9 10 public class Main17 { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 15 } 16 17 public class TreeNode { 18 int val = 0; 19 TreeNode left = null; 20 TreeNode right = null; 21 22 public TreeNode(int val) { 23 this.val = val; 24 25 } 26 27 } 28 29 public boolean HasSubtree(TreeNode root1,TreeNode root2) { 30 if (root1 == null || root2 == null) { 31 return false; 32 } 33 return isSubtree(root1,root2) || HasSubtree(root1.left,root2) || HasSubtree(root1.right, root2); 34 } 35 36 public boolean isSubtree(TreeNode root1, TreeNode root2) { 37 if (root2 == null) { 38 return true; 39 } 40 if (root1 == null) { 41 return false; 42 } 43 44 if (root1.val == root2.val) { 45 return isSubtree(root1.left,root2.left) && isSubtree(root1.right,root2.right); 46 }else { 47 return false; 48 } 49 } 50 51 }