题目:
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
代码:
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def helper(in_left, in_right):
nonlocal pre_idx
# 如果没有元素可以构造
if in_left == in_right:
return None
# 把前序遍历的元素作为树根
root_val = preorder[pre_idx]
root = TreeNode(root_val)
# 根分裂中序遍历列表分为左右子树
index = idx_map[root_val]
# 递归
pre_idx += 1
# 构建左子树
root.left = helper(in_left, index)
# 构建右子树
root.right = helper(index + 1, in_right)
return root
# 从第一个前序遍历元素开始
pre_idx = 0
# 建立一个哈希表
idx_map = {val: idx for idx, val in enumerate(inorder)}
return helper(0, len(inorder))