题目
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
解题思路
简而言之一句话,“先序找根,划分左右”。具体的,通过先序遍历我们可以找到root,根据root我们可以在中序遍历中找到当前root对应的左右子树,再递归对当前root的左右子树进行构造。所以构建二叉树的问题流程就是:
1)找到各个子树的根节点 root;
2)构建该根节点的左子树;
3)构建该根节点的右子树。
复杂度分析:
时间复杂度:O(n),其中 n 是树中的节点个数。(注:Java解法中用到了 O(n) 的空间存储哈希映射,来保存根节点索引,加快了查找速度。而Python这里的解法没有利用哈希映射,时间复杂度为O(n^2)。)
空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为 O(n)。
(类似题目:106. 从中序与后序遍历序列构造二叉树)
代码
Python代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder or not inorder: # 递归终止条件,
return None
# 在preorder中找到根节点root
root = TreeNode(preorder[0])
# 在inorder中找到根节点的索引,来划分左右子树
root_idx = inorder.index(preorder[0])
# 递归地构建左子树
root.left = self.buildTree(preorder[1:root_idx+1], inorder[:root_idx])
# 递归地构建右子树
root.right = self.buildTree(preorder[root_idx+1:], inorder[root_idx+1:])
return root
Java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode myBuildTree(int[] preorder, int[] inorder, int preleft, int preright, int inleft, int inright, Map<Integer, Integer> map){
if(preleft > preright || inleft > inright){
return null;
}
TreeNode root = new TreeNode(preorder[preleft]);
int root_idx = map.get(preorder[preleft]);
root.left = myBuildTree(preorder, inorder, preleft+1, root_idx-inleft+preleft, inleft, root_idx-1, map);
root.right = myBuildTree(preorder, inorder, root_idx-inleft+preleft+1, preright, root_idx+1, inright, map);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<n; i++){
map.put(inorder[i], i);
}
return myBuildTree(preorder, inorder, 0, n-1, 0, n-1, map);
}
}