diff --git a/Leetcode/100.same_tree.py b/Leetcode/100.same_tree.py index beb14417..e3ec7b96 100644 --- a/Leetcode/100.same_tree.py +++ b/Leetcode/100.same_tree.py @@ -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))