原题地址:http://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题意:根据二叉树的先序遍历和中序遍历恢复二叉树。
解题思路:可以参照 http://www.cnblogs.com/zuoyuan/p/3720138.html 的思路。递归进行解决。
代码:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param preorder, a list of integers # @param inorder, a list of integers # @return a tree node def buildTree(self, preorder, inorder): if len(preorder) == 0: return None if len(preorder) == 1: return TreeNode(preorder[0]) root = TreeNode(preorder[0]) index = inorder.index(root.val) root.left = self.buildTree(preorder[1 : index + 1], inorder[0 : index]) root.right = self.buildTree(preorder[index + 1 : len(preorder)], inorder[index + 1 : len(inorder)]) return root
[leetcode]Construct Binary Tree from Preorder and Inorder Traversal @ Python,布布扣,bubuko.com
[leetcode]Construct Binary Tree from Preorder and Inorder Traversal @ Python