Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit245ed81

Browse files
Merge pull requestneetcode-gh#258 from monkey-patcher/105-leetcode-fix
105-leetcode create binary tree from traversals/Use of dictionary
2 parentsca36cec +c964b9a commit245ed81

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
classSolution:
22
defbuildTree(self,preorder:List[int],inorder:List[int])->Optional[TreeNode]:
3-
ifnotpreorderornotinorder:
4-
returnNone
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-
returnroot
3+
inorder_index_mapping= {}
4+
fork,vinenumerate(inorder):
5+
inorder_index_mapping[v]=k
6+
index=0
7+
defbuildtree(left,right):
8+
nonlocalindex
9+
ifleft>right:
10+
returnNone
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+
returnroot
17+
returnbuildtree(0,len(preorder)-1)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp