遍历A时用bfs,判断以A的每个节点为根的树是否包含B(B的根和该子节点重合)用dfs
func hasSubtree(t1 *TreeNode, t2 *TreeNode) bool {
if t1 == nil || t2 == nil {
return false
}
q := list.New()
q.PushBack(t1)
for q.Len() > 0 {
t := q.Remove(q.Front()).(*TreeNode)
if isRootChild(t, t2) {
return true
}
if t.Left != nil {
q.PushBack(t.Left)
}
if t.Right!= nil {
q.PushBack(t.Right)
}
}
return false
}
func isRootChild(t1, t2 *TreeNode) bool {
if t2 == nil {
return true
}
if t1 == nil {
return false
}
if t1.Val != t2.Val {
return false
}
return isRootChild(t1.Left, t2.Left) && isRootChild(t1.Right, t2.Right)
}