思路:采用先序遍历的思想遍历二叉树。
- public boolean isSubtree(TreeNode root, TreeNode subRoot) {
- if(root==null) return false;
- return helper(root,subRoot)||isSubtree(root.left,subRoot)||isSubtree(root.right,subRoot);
- }
-
- private boolean helper(TreeNode root,TreeNode subRoot){
- if(root==null&&subRoot==null) return true;
- if(root==null||subRoot==null) return false;
- if(root.val!=subRoot.val) return false;
- return helper(root.left,subRoot.left)&&helper(root.right,subRoot.right);
- }