File tree Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Expand file tree Collapse file tree 1 file changed +19
-0
lines changed Original file line number Diff line number Diff line change
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
+ return False
17
+
18
+ # recursively check both left and right subtrees
19
+ return self .isSameTree (p .left , q .left ) and self .isSameTree (p .right , q .right )
You can’t perform that action at this time.
0 commit comments