二叉树的子结构-这题很有趣,递归套递归

树的子结构

http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88

/**
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(root2==null||root1==null){
            return false;
        }
        return dfs(root1,root2)||HasSubtree(root1.left,root2)||HasSubtree(root1.right,root2);
    }
    boolean dfs(TreeNode r1,TreeNode r2){
        if(r2==null)return true;
        if(r1==null)return false;
        boolean result=true;
        if(r1.val!=r2.val)
            result=false;
        boolean result1=dfs(r1.left,r2.left);
        boolean result2=dfs(r1.right,r2.right);
        return result&&result1&&result2;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务