Construct Binary Tree from Inorder and Preorder
题目描述
Given inorder and preorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
解题方法
递归
过不了Leetcode OJ
Solution
递归
python的递归过不了OJ, java的可以……
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder or not inorder:
return
root = TreeNode(preorder[0])
indexIn = inorder.index(root.val)
root.left = self.buildTree(preorder[1:indexIn+1], inorder[:indexIn])
root.right = self.buildTree(preorder[indexIn+1:], inorder[indexIn+1:])
return root