Skip to content

Commit 4869155

Browse files
authored
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)
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