[LeetCode]题解(python):105-Construct Binary Tree from Preorder and Inorder Traversal
题目来源:
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题意分析:
根据二叉树的中序和前序遍历结果,反推这个树,假设只有一个这样的树。
题目思路:
前序遍历的第一个树将中序遍历分成两半,左半部分是左子树,右半部分是右子树,递归重构这棵树。
代码(python):
# 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 """ def dfs(pbegin,pend,ibegin,iend): if pbegin >= pend: return None if pbegin + 1 == pend: return TreeNode(preorder[pbegin]) i = inorder.index(preorder[pbegin]) i -= ibegin ans = TreeNode(preorder[pbegin]) ans.left = dfs(pbegin + 1,pbegin + i + 1,ibegin,ibegin+i) ans.right = dfs(pbegin + i + 1,pend,ibegin + 1 + i,iend) return ans return dfs(0,len(preorder),0,len(inorder))