File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments