2023-9-28 JZ26 树的子结构

题目链接:树的子结构

2023-9-28 JZ26 树的子结构_第1张图片

import java.util.*;
/**
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) {
        if(root1 == null || root2 == null) return false;
        if(isPart(root1, root2)) return true;
        return HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
    }

    public boolean isPart(TreeNode p1, TreeNode p2){
        if(p2 == null) return true;
        if(p1 == null || p1.val != p2.val) return false;
        return isPart(p1.left, p2.left) && isPart(p1.right, p2.right);
    }

}

你可能感兴趣的:(树,剑指offer)