1008. 先序遍历构造二叉树
输入:[8,5,1,7,10,12]输出:[8,5,10,1,7,null,12]
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def bstFromPreorder(self, preorder): 10 """ 11 :type preorder: List[int] 12 :rtype: TreeNode 13 """ 14 if len(preorder)==0: return None 15 if len(preorder)==1: return TreeNode(preorder[0]) 16 17 root = TreeNode(preorder[0]) 18 idx=1 19 while idx<len(preorder) and preorder[idx]<preorder[0]: 20 idx+=1 21 root.left = self.bstFromPreorder(preorder[1:idx]) 22 root.right = self.bstFromPreorder(preorder[idx:]) 23 return root 24 25