Skip to content

Latest commit

 

History

History
37 lines (31 loc) · 1.19 KB

26. 树的子结构.md

File metadata and controls

37 lines (31 loc) · 1.19 KB

解题思路

1. 内外一起迭代

isSubStructure 做外层树的遍历,B 保持不变,遍历 A 的每个节点,以 A 的每个节点作为起始点,去和 B 做对比 dfs 做内层树的遍历,A 和 B 一起走,判断每个节点是否相等,当 B 为 nil,说明比较完成了

func isSubStructure(A, B *TreeNode) bool {
    if A == nil || B == nil {
        return false
    }
    // dfs 当前的 A 结构和 B 进行比较
    // isSubStructure 遍历 A 的其他节点
    // || 只要从某一个节点能成功完成结果为 true 的对比,说明 B 就是 A 的子结构
    return dfs(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, B)
}

func dfs(A, B *TreeNode) bool {
    // 当遍历到 B 为 nil,说明该路径判断完成,返回 true
    if B == nil {
        return true
    }
    // 如果 B != nil 但是 A == nil 了,肯定 false
    // 值不相等也是 false
    if A == nil || A.Val != B.Val {
        return false
    }
    // A B 一起遍历比较下一轮
    // && 必须子树比较结果都为 true,才能说确实是子结构
    return dfs(A.Left, B.Left) && dfs(A.Right, B.Right)
}