面试题26. 树的子结构

https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/

func isSubStructure(_ A: TreeNode?, _ B: TreeNode?) -> Bool {
    if A == nil ||  B == nil {return false}
    //找到相同的跟节点
    if A?.val == B?.val {
        //比较子节点
        return hasSubTree(A, B)
    } else {
        //寻找是否有相同的节点
        return isSubStructure(A?.left, B) || isSubStructure(A?.right, B)
    }
}

func hasSubTree(_ A: TreeNode?, _ B: TreeNode?) -> Bool {
    if B == nil {return true}
    if A == nil || A?.val != B?.val {return false}
    return hasSubTree(A?.left, B?.left) && hasSubTree(A?.right, B?.right)
}

你可能感兴趣的:(面试题26. 树的子结构)