Skip to content

Commit bb6378c

Browse files
committed
add solution: same-tree
1 parent ef969af commit bb6378c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

same-tree/dusunax.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
# 100. Same Tree
3+
4+
## Base case
5+
- if both nodes are None, return True
6+
- if one of the nodes is None, return False
7+
- if the values of the nodes are different, return False
8+
9+
## Recursive case
10+
- check if the left subtrees are the same
11+
- check if the right subtrees are the same
12+
13+
## Time and Space Complexity
14+
15+
```
16+
TC: O(n)
17+
SC: O(n)
18+
```
19+
20+
#### TC is O(n):
21+
- visiting each node once, balanced or skewed, it's O(n)
22+
23+
#### SC is O(n):
24+
- for h is tree's height.
25+
- in best case(balanced): h is logN, so SC is O(logN)
26+
- in worst case(skewed): h is N, so SC is O(N)
27+
'''
28+
class Solution:
29+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
30+
if not p and not q:
31+
return True
32+
if not p or not q:
33+
return False
34+
if p.val != q.val:
35+
return False
36+
37+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

0 commit comments

Comments
 (0)