通过一棵二叉树的中序和后序排列来得出它的树形结构。
注意点:
例子:
输入: inorder = [9,3,14,15,20,7], postorder = [9,14,15,7,20,3]
输出:
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, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
self.postorder = postorder
self.inorder = inorder
return self._buildTree(0, len(inorder))
def _buildTree(self, start, end):
if start < end:
root = TreeNode(self.postorder.pop())
index = self.inorder.index(root.val)
root.right = self._buildTree(index + 1, end)
root.left = self._buildTree(start, index)
return root
if __name__ == "__main__":
None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
LeetCode Construct Binary Tree from Inorder and Postorder Traversal
原文:http://blog.csdn.net/u013291394/article/details/50688456