We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent cf5691a commit a002894Copy full SHA for a002894
1 file changed
same-tree/yolophg.py
@@ -0,0 +1,19 @@
1
+# Time Complexity: O(N) - visit each node once.
2
+# Space Complexity: O(N) in the worst case (skewed tree), O(log N) in the best case (balanced tree).
3
+
4
+class Solution:
5
+ def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
6
+ # if both trees are empty, they are obviously the same
7
+ if p is None and q is None:
8
+ return True
9
10
+ # if one tree is empty but the other is not, they can't be the same
11
+ if p is None or q is None:
12
+ return False
13
14
+ # if values of the current nodes are different, trees are not the same
15
+ if p.val != q.val:
16
17
18
+ # recursively check both left and right subtrees
19
+ return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
0 commit comments