Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 17 additions & 21 deletions Leetcode/100.same_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,26 @@ def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def isSameTree(self, p, q):
if p is None:
if q is None:
return True #both tree are empty
else:
return False #one tree is empty(p) and other is non-empty(q)
if q is None:
if p is None:
return True #both tree are empty
else:
return False #one tree is empty(q) and other is non-empty(p)
if p.val != q.val:
return False #value of node not equal means not same
# Base case: if both nodes are None, they are the same
if p is None and q is None:
return True

return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
#recursion on lst and rst if both true then trees are same
# If one of the nodes is None, they are different
if p is None or q is None:
return False

# If the values of the nodes are not equal, they are different
if p.val != q.val:
return False

# Recur for left and right subtrees
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

# Example usage
opt = Solution()
root = TreeNode(1)
root1 = TreeNode(1)
root.left = TreeNode(2)
root1.left = TreeNode(2)
root.right = TreeNode(3)
root1.right = TreeNode(3)
print(opt.isSameTree(root,root1))
root = TreeNode(1, TreeNode(2), TreeNode(3))
root1 = TreeNode(1, TreeNode(2), TreeNode(3))
print(opt.isSameTree(root, root1))