思路很简单:先找到匹配的根节点,再在树1的左子树和右子树里面进行遍历
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public boolean HasSubtree(TreeNode root1,TreeNode root2) { boolean result = false; if(root1!=null && root2!=null){ if(root1.val==root2.val){ result = DoesTreeHasNextTree(root1,root2); } if(!result){ result = HasSubtree(root1.left,root2); } if(!result){ result = HasSubtree(root1.right,root2); } } return result; } public static boolean DoesTreeHasNextTree(TreeNode t1,TreeNode t2){ if(t2==null){ return true; } if(t1==null){ return false; } if(t1.val!=t2.val){ return false; } return DoesTreeHasNextTree(t1.left,t2.left)&&DoesTreeHasNextTree(t1.right,t2.right); } }