难度中等1404收藏分享切换为英文接收动态反馈
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
-
preorder
和inorder
均 无重复 元素 -
inorder
均出现在preorder
-
preorder
保证 为二叉树的前序遍历序列 -
inorder
保证 为二叉树的中序遍历序列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_map<int,int>inorderId;
public:
TreeNode* buildTree(vector<int>& preorder,vector<int>& inorder,int preorder_left,int preorder_right,int inorder_left,int inorder_right){
if(preorder_left>preorder_right) return nullptr;
int rootValue=preorder[preorder_left];
int root_inorder=inorderId[rootValue];
int leftTreeSize=root_inorder-inorder_left;
TreeNode* newRoot=new TreeNode(rootValue);
newRoot->left=buildTree(preorder,inorder,preorder_left+1,preorder_left+leftTreeSize,inorder_left,root_inorder-1);
newRoot->right=buildTree(preorder,inorder,preorder_left+leftTreeSize+1,preorder_right,root_inorder+1,inorder_right);
return newRoot;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=preorder.size();
for(int i=0;i<n;i++) inorderId[inorder[i]]=i;
return buildTree(preorder,inorder,0,n-1,0,n-1);
}
};