Subtree of a Binary Tree

Problem Statement:

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Example:

Pasted image 20260210184729.png

Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true

Intuition:

Firstly visit Same Tree,.
Intuition is, go for every node of large tree and check for every node as root and to the other sub-tree.


Code:

My Solution


def isSubTree(root1, root2):
	def isSame(p, q):
		if not p and not q:
			return True
		
		if p and q and p.val == q.val:
			return (isSame(p.left, q.left) and isSame(p.right, q.right))
		
		return False
		
	def dfs(node):
		if not node:
			return False
		
		if isSame(node, root2) or dfs(node.left) or dfs(node.right):
			return True
		
		return False

#binary-tree #dsa