【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal
题目如下:
解题思路:根据先序和中序遍历的结果构造二叉树,这也是二叉树系列题目中的经典题型了。这种题目用递归比较简单,先序遍历是先遍历根节点,如题目用例中的3根节点,而中序遍历根节点在中间,所以以3作为分割点把中序的结果分割成[9]和[15,20,7],这两半部分分别对应根节点的左右子树,接下来再对左右子树分别做同样的递归即可,这里需要注意的是先递归左子树,再是右子树,因为先序遍历就是先左后右的,相同的顺序可以保证先序结果中preorder.pop(0)出来的节点都是即将要递归的子树的根节点。
代码如下:
# 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 traverse(self,parent,preorder,inorder,director): if len(preorder) == 0 or len(inorder) == 0: return node = TreeNode(preorder.pop(0)) if director == 'L': parent.left = node else: parent.right = node inx = inorder.index(node.val) self.traverse(node, preorder, inorder[0:inx], 'L') self.traverse(node, preorder, inorder[inx + 1:], 'R') def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if len(preorder) == 0 or len(inorder) == 0: return None root = TreeNode(preorder.pop(0)) inx = inorder.index(root.val) self.traverse(root,preorder,inorder[0:inx],'L') self.traverse(root,preorder,inorder[inx+1:],'R') return root