剑指offer_树的子结构

输入两棵二叉树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 if(root1==null || root2==null) return false; 17 return isTree(root1,root2)||isTree(root1.left,root2)||isTree(root1.right,root2); 18 } 19 public boolean isTree(TreeNode root1,TreeNode root2){ 20 if(root2==null) return true; 21 if(root1==null) return false; 22 if(root1.val!=root2.val) return false; 23 return isTree(root1.left,root2.left)&&isTree(root1.right,root2.right); 24 } 25 26 27 }

浙公网安备 33010602011771号