leetcode算法题--树的子结构

原题链接:https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/description/?envType=study-plan-v2&envId=coding-interviews

是一个dfs的题目,但是一开始的方法写的有点麻烦

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSubStructure(A *TreeNode, B *TreeNode) bool {
    if B == nil {
        return false
    }

    var dfs func(node1 *TreeNode, node2 *TreeNode) bool 
    dfs = func(node1 *TreeNode, node2 *TreeNode) bool {
        if node2 == nil {
           return true 
        } 
        
        if node1 == nil {
            return false
        }

        flag1, flag2 := false, false
        if node1.Val == node2.Val {
            flag1 = dfs(node1.Left, node2.Left) && dfs(node1.Right, node2.Right)
        }
        flag2 = dfs(node1.Left, B) || dfs(node1.Right, B)
        return flag1 || flag2
    }
    return dfs(A, B)
}

优化,这种会涉及到“从头开始”的题目,应该要想到调用原函数

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isSubStructure(A *TreeNode, B *TreeNode) bool {
    var dfs func(node1 *TreeNode, node2 *TreeNode) bool 
    dfs = func(node1 *TreeNode, node2 *TreeNode) bool {
        if node2 == nil {
           return true 
        } 
        
        if node1 == nil {
            return false
        }

        return (node1.Val == node2.Val) && dfs(node1.Left, node2.Left) && dfs(node1.Right, node2.Right)
    }
    return (A != nil && B!= nil) && (dfs(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, B))
}

你可能感兴趣的:(Algorithm,算法,leetcode,深度优先)