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

Commit 4869155

Browse files
Create constructBinaryTreePreorderInOrder.py
1 parent 035c438 commit 4869155

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
sample 355 ms submission
2+
# Definition for a binary tree node.
3+
# class TreeNode(object):
4+
# def __init__(self, x):
5+
# self.val = x
6+
# self.left = None
7+
# self.right = None
8+
class Solution(object):
9+
def buildTree(self, preorder, inorder):
10+
"""
11+
:type preorder: List[int]
12+
:type inorder: List[int]
13+
:rtype: TreeNode
14+
"""
15+
# 若是len(preorder)為0 則返回空
16+
# 首次輸入邊界條件
17+
if len(preorder) == 0:
18+
return None
19+
# 遞歸edge
20+
# 若是長度為1 則返回當前值
21+
if len(preorder) == 1:
22+
return TreeNode(preorder[0])
23+
root = TreeNode(preorder[0])
24+
# 從preorder的第一個找出 inorder的index
25+
index = inorder.index(root.val)
26+
27+
# 記得切片不包括尾數 左閉右開 -> [1:0]==[]
28+
root.left = self.buildTree(preorder[1:index+1], inorder[0:index])
29+
root.right = self.buildTree(preorder[index+1:], inorder[index+1:])
30+
return root

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /