Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
下面的代码内存超了,看了人家的,改成了这样。
一定要搞清前序中序是什么意思。
# 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):
if inorder:
val = preorder.pop(0)
pos = inorder.index(val)
root = TreeNode(val)
root.left = self.buildTree(preorder,inorder[:pos])
root.right = self.buildTree(preorder,inorder[pos+1:])
return root
'''
if not p:
return None
#print p,i,i.index(p[0])
if len(p) == 1:
return TreeNode(p[0])
val = p[0]
pos = i.index(val)
root = TreeNode(val)
root.left = self.buildTree(p[1:pos+1],i[0:pos])
root.right = self.buildTree(p[pos+1:],i[pos+1:])
return root
'''
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""