通过一棵二叉树的前序和中序排列来得出它的树形结构。
注意点:
例子:
输入: preorder = [3,9,20,15,14,7], inorder = [9,3,14,15,20,7]
输出:
3
/ 9 20
/ 15 7
/
14
开始递归的时候用了列表作为参数,结果内存溢出,改用下标作参数,先序和中序序列作为全局变量。
# 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
"""
self.preorder = preorder
self.inorder = inorder
return self._buildTree(0, len(preorder), 0, len(inorder))
def _buildTree(self, pre_start, pre_end, in_start, in_end):
if pre_start >= pre_end:
return None
root = TreeNode(self.preorder[pre_start])
offset = self.inorder[in_start:in_end + 1].index(root.val)
root.left = self._buildTree(pre_start + 1, pre_start + offset + 1, in_start, in_start + offset)
root.right = self._buildTree(pre_start + offset + 1, pre_end, in_start + offset + 1, in_end)
return root
if __name__ == "__main__":
None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
LeetCode Construct Binary Tree from Preorder and Inorder Traversal
原文:http://blog.csdn.net/u013291394/article/details/50678202