File tree Expand file tree Collapse file tree 2 files changed +23
-16
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal
encode-and-decode-strings Expand file tree Collapse file tree 2 files changed +23
-16
lines changed Original file line number Diff line number Diff line change
1
+ # Definition for a binary tree node.
2
+ from typing import List
3
+
4
+
5
+ class TreeNode :
6
+ def __init__ (self , val = 0 , left = None , right = None ):
7
+ self .val = val
8
+ self .left = left
9
+ self .right = right
10
+
11
+ class Solution :
12
+ # time complexity: O(n)
13
+ # space complexity: O(n)
14
+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
15
+ if not preorder or not inorder :
16
+ return None
17
+
18
+ val = preorder .pop (0 )
19
+ mid = inorder .index (val )
20
+ left = self .buildTree (preorder , inorder [:mid ])
21
+ right = self .buildTree (preorder , inorder [mid + 1 :])
22
+
23
+ return TreeNode (val , left , right )
Original file line number Diff line number Diff line change 1
1
class Solution1 :
2
- """
3
- @param: strs: a list of strings
4
- @return: encodes a list of strings to a single string.
5
- """
6
2
# time complexity: O(n)
7
3
# space complexity: O(1)
8
4
def encode (self , strs ):
9
5
return ":;" .join (strs )
10
6
11
- """
12
- @param: str: A string
13
- @return: decodes a single string to a list of strings
14
- """
15
7
# time complexity: O(n)
16
8
# space complexity: O(1)
17
9
def decode (self , str ):
18
10
return str .split (":;" )
19
11
20
12
class Solution2 :
21
- """
22
- @param: strs: a list of strings
23
- @return: encodes a list of strings to a single string.
24
- """
25
13
# time complexity: O(n)
26
14
# space complexity: O(1)
27
15
def encode (self , strs ):
@@ -30,10 +18,6 @@ def encode(self, strs):
30
18
txt += str (len (s )) + ":" + s
31
19
return txt
32
20
33
- """
34
- @param: str: A string
35
- @return: decodes a single string to a list of strings
36
- """
37
21
# time complexity: O(n)
38
22
# space complexity: O(1)
39
23
def decode (self , str ):
You can’t perform that action at this time.
0 commit comments