I implemented a recursive solution in Python to check if two binary trees are identical, which traverses nodes recursively and compares values and structure. The time complexity is O(n), space O(h).
Here is my code:
class TreeNode:
def __init__(self, key=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
def isSameTree(p: TreeNode, q: TreeNode) -> bool:
if p is None and q is None:
return True #just if both are empty
#if both are not empty and nodes dont match, recur the left and right subtree
return (p is not None and q is not None) and (p.key == q.key) and \
isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
p = TreeNode(1)
q = TreeNode(1)
print(isSameTree(p, q))
Is there a faster algorithm? Is there a way to optimize memory usage? Is there an iterative alternative that is more practical?
#if both are not empty and nodes dont match, recur the left and right subtreeis wrong