/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int,int>pos;
TreeNode *dfs(vector<int>& pre,vector<int>& in,int pl,int pr,int il,int ir)
{
if(pl>pr)return nullptr;//递归出口,当前序遍历的区间不满足就返回;
TreeNode *root=new TreeNode(pre[pl]);//创建根节点
int k=pos[pre[pl]]-il;//根节点在中序数组的位置
root->left=dfs(pre,in,pl+1,pl+k,il,il+k-1);
root->right=dfs(pre,in,pl+k+1,pr,il+k+1,ir);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=inorder.size();
for(int i=0;i<n;i++)pos[inorder[i]]=i;//哈希存储元素位置
return dfs(preorder,inorder,0,n-1,0,n-1);
}
};
leetcode 105. 从前序与中序遍历序列构造二叉树
最新推荐文章于 2022-10-30 11:23:48 发布