Same Tree
Problem: Same Tree
This is a typical depth-first search problem so no need to explain more. You can also use stacks to solve this problem instead of complex and time-consuming recursion.
Code in Python:
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q: return True
elif p and q:
if p.val == q.val:
if p.left and q.left:
if self.isSameTree(p.left, q.left):
if p.right and q.right:
return self.isSameTree(p.right, q.right)
elif not p.right and not q.right:
return True
elif not p.left and not q.left:
if p.right and q.right:
return self.isSameTree(p.right, q.right)
elif not p.right and not q.right:
return True
return False