使用递归,判断每一个是否匹配,匹配返回true,全部都不匹配返回false
-
-
- /**
- * @author xienl
- * @description 判断t1树中是否有与t2树完全相同的子树
- * @date 2022/7/1
- */
-
- public class Solution {
- public static void main(String[] args) {
- Solution solution = new Solution();
-
- }
-
- public boolean isContains (TreeNode root1, TreeNode root2) {
- // write code here
- if (root1 == null){
- return false;
- }
- return calculation(root1, root2) || isContains(root1.left, root2) || isContains(root1.right, root2);
- }
-
- private boolean calculation(TreeNode root1, TreeNode root2){
- if (root1 == null && root2 == null){
- return true;
- }
- if (root1 == null || root2 == null || (root1.val != root2.val)){
- return false;
- }
- return calculation(root1.left, root2.left) && calculation(root1.right , root2.right);
- }
- }
-
-
- class TreeNode {
- int val = 0;
- TreeNode left = null;
- TreeNode right = null;
- }