Solution 1 - DFS + Same-Tree Check
Try matching subRoot at every node in root.
Try matching subRoot at every node in root.
""" 0572.1 - Subtree of Another Tree - Solution 1 - DFS """
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not subRoot:
return True
if not root:
return False
return self.same(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
def same(self, a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
if not a or not b:
return a is b
return a.val == b.val and self.same(a.left, b.left) and self.same(a.right, b.right)package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func same(a, b *TreeNode) bool {
if a == nil || b == nil {
return a == b
}
return a.Val == b.Val && same(a.Left, b.Left) && same(a.Right, b.Right)
}
func isSubtree(root, subRoot *TreeNode) bool {
if subRoot == nil {
return true
}
if root == nil {
return false
}
return same(root, subRoot) || isSubtree(root.Left, subRoot) || isSubtree(root.Right, subRoot)
}
func main() {}