题解 | #树的子结构#

树的子结构

https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88

/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param pRoot1 TreeNode类 
 * @param pRoot2 TreeNode类 
 * @return bool布尔型
 */
export function HasSubtree(pRoot1: TreeNode, pRoot2: TreeNode): boolean {
    //这个是判断是否pRoot1中是否有pRoot2的节点(根节点)
    if(!pRoot1||!pRoot2){
        return false
    }

    //判断是否当前节点的左右子树是否想的
    //判断pRoot1的左子树与目标树是否相等
    //判断pRoot1 的右子树与目标树是否相等
    return isSame(pRoot1,pRoot2)||HasSubtree(pRoot1.left,pRoot2)||HasSubtree(pRoot1.right,pRoot2)
}
//判断子树是否相等
function isSame (pRoot1:TreeNode,pRoot2:TreeNode):boolean{
    if(!pRoot2){
        return true
    }else if(!pRoot1){
        return false
    }
    if(pRoot1.val !== pRoot2.val){
        return false
    }
    return isSame(pRoot1.left,pRoot2.left)&&isSame(pRoot1.right,pRoot2.right)

}

全部评论

相关推荐

10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
被子有点短:有了实习后会发现有实习也没用
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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