Check out the problem description here.
Same Tree - LeetCode
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees…
Recursively traverse the tree. Here we check if the right subtree, right sub tree and the current node in the first tree is same as that of the second tree.
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p==None and q==None:
if(p==None or q==None):
if p.val == q.val:
return(self.rec(p.left,q.left) and self.isSameTree(p.right,q.right))
Time: O(N) -> N is the number of the nodes in first or second tree
Space: O(log(N)) that is the depth of tree, which is the auxiliary space for the stack calls.