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 11class Solution1 :
2- """
3- @param: strs: a list of strings
4- @return: encodes a list of strings to a single string.
5- """
62 # time complexity: O(n)
73 # space complexity: O(1)
84 def encode (self , strs ):
95 return ":;" .join (strs )
106
11- """
12- @param: str: A string
13- @return: decodes a single string to a list of strings
14- """
157 # time complexity: O(n)
168 # space complexity: O(1)
179 def decode (self , str ):
1810 return str .split (":;" )
1911
2012class Solution2 :
21- """
22- @param: strs: a list of strings
23- @return: encodes a list of strings to a single string.
24- """
2513 # time complexity: O(n)
2614 # space complexity: O(1)
2715 def encode (self , strs ):
@@ -30,10 +18,6 @@ def encode(self, strs):
3018 txt += str (len (s )) + ":" + s
3119 return txt
3220
33- """
34- @param: str: A string
35- @return: decodes a single string to a list of strings
36- """
3721 # time complexity: O(n)
3822 # space complexity: O(1)
3923 def decode (self , str ):
You can’t perform that action at this time.
0 commit comments