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)
}
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/17017544.html