leetcode-572. 另一棵树的子树

https://leetcode.cn/problems/subtree-of-another-tree/description/

需要有两个不同的递归,如果当前节点的值和另一棵树的root.Val相同,那么需要判断两棵树是否完全相等

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSubtree(root *TreeNode, subRoot *TreeNode) bool {
    if subRoot == nil {
        return true
    }
    if root == nil && subRoot != nil {
        return false
    }

    if root.Val == subRoot.Val && isSametree(root, subRoot) {
        return true
    }

    return isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot)
}

func isSametree(root *TreeNode, subRoot *TreeNode) bool {
    if root == nil && subRoot == nil {
        return true
    } else if (root != nil && subRoot == nil) || (root == nil && subRoot != nil) {
        return false
    }

    if root.Val != subRoot.Val {
        return false
    }

    return isSametree(root.Left, subRoot.Left) && isSametree(root.Right, subRoot.Right)
}
posted @ 2022-12-31 23:04  吴丹阳-V  阅读(17)  评论(0编辑  收藏  举报