Skip to content

Commit c964b9a

Browse files
PytoPyto
authored andcommitted
simple change for better complexity
1 parent 51bcb14 commit c964b9a

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed
Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
class Solution:
22
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
3-
if not preorder or not inorder:
4-
return None
5-
6-
root = TreeNode(preorder[0])
7-
mid = inorder.index(preorder[0])
8-
root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
9-
root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])
10-
return root
3+
inorder_index_mapping = {}
4+
for k,v in enumerate(inorder):
5+
inorder_index_mapping[v] = k
6+
index = 0
7+
def buildtree(left,right):
8+
nonlocal index
9+
if left>right:
10+
return None
11+
root_val=preorder[index]
12+
root = TreeNode(root_val)
13+
index+=1
14+
root.left = buildtree(left, inorder_index_mapping[root_val]-1)
15+
root.right = buildtree(inorder_index_mapping[root_val]+1, right)
16+
return root
17+
return buildtree(0, len(preorder)-1)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy