Skip to content

Commit 5dd8db8

Browse files
committed
[LC] feat: 240825 construct binary tree from preorder and inorder traversal
1 parent 605c596 commit 5dd8db8

File tree

2 files changed

+23
-16
lines changed

2 files changed

+23
-16
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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)

encode-and-decode-strings/hajunyoo.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,15 @@
11
class 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

2012
class 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):

0 commit comments

Comments
 (0)