「安全プランを証明する」サブツリー(ジャワ)

タイトル説明

二つのバイナリ入力はA、B、BはAさんを下部ではないと判断されます。(詩:私たちは、空のツリーは任意のサブ構造ツリーではありません同意しました)

ACコード

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
//如果是空树,返回false
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 r1,TreeNode r2){
        if(r2==null)
            return true;
        if(r1==null||(r1.val!=r2.val))
            return false;
        return isPart(r1.left,r2.left)&&isPart(r1.right,r2.right);
    }
}

公開された98元の記事 ウォンの賞賛5 ビュー7467

おすすめ

転載: blog.csdn.net/weixin_40992982/article/details/104101016