输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
1 /** 2 public class TreeNode { 3 int val = 0; 4 TreeNode left = null; 5 TreeNode right = null; 6 7 public TreeNode(int val) { 8 this.val = val; 9 10 } 11 12 } 13 */ 14 public class Solution { 15 public boolean HasSubtree(TreeNode root1,TreeNode root2) { 16 17 boolean result = false; 18 19 if(root1 != null && root2 != null){ 20 21 if(root1.val == root2.val){ 22 result = DoesTree1HasTree2(root1,root2); 23 } 24 25 //递归遍历左子树 26 if(!result){ 27 result = HasSubtree(root1.left, root2); 28 } 29 30 //递归遍历右子树 31 if(!result){ 32 result = HasSubtree(root1.right, root2); 33 } 34 } 35 36 return result; 37 38 } 39 40 41 public boolean DoesTree1HasTree2(TreeNode root1,TreeNode root2){ 42 43 if(root2 == null){ 44 return true; 45 } 46 47 if(root1 == null){ 48 return false; 49 } 50 51 if(root1.val != root2.val){ 52 return false; 53 } 54 55 return DoesTree1HasTree2(root1.left, root2.left) && DoesTree1HasTree2(root1.right, root2.right); 56 } 57 }