剑指 Offer 07. 重建二叉树
题意:使用二叉树的前序遍历和中序遍历构建二叉树;
思路:根据两种排序的特点,得到构造方式(通过前序判断端点,根据中序和前序判断孩子节点)
我写了两种写法,一次对中序中节点在前序的位置做了预处理,一次没有,时间差别比较大。
不做预处理 236ms 24.9M(37%)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
map<int,int>mapp;
int n;
vector<int>preorder,inorder;
void dfs(TreeNode*& wrk,int cnt,int lef,int rig)
{
//cout<<inorder[0]<<preorder[cnt+1];
//cout<<lef<<rig<<mapp[cnt];
int ppre=preorder[cnt];
for(int i=lef;i<mapp[ppre];i++)
if(inorder[i]==preorder[cnt+1])
{
wrk->left=new TreeNode(preorder[cnt+1]);
dfs(wrk->left,cnt+1,lef,mapp[ppre]-1);
break;
}
int pos=cnt+mapp[ppre]-lef+1;
if(pos>=0&&pos<n&&mapp[preorder[pos]]<=rig&&mapp[preorder[pos]]>mapp[ppre])
{
wrk->right=new TreeNode(preorder[pos]);
dfs(wrk->right,pos,mapp[ppre]+1,rig);
}
return;
}
class Solution {
public:
TreeNode* buildTree(vector<int>& pre, vector<int>& ino) {
n=pre.size();
preorder=pre;
inorder=ino;
for(int i=0;i<n;i++)
mapp[inorder[i]]=i;
TreeNode* ans=NULL;
if(!n)return ans;
ans=new TreeNode(preorder[0]);
dfs(ans,0,0,n-1);
return ans;
}
};
做了预处理 16ms(86%) 24.7M(63%)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
map<int,int>mapp;
int n;
vector<int>preorder,inorder;
void dfs(TreeNode*& wrk,int cnt,int lef,int rig)
{
//cout<<inorder[0]<<preorder[cnt+1];
//cout<<lef<<rig<<mapp[cnt];
int ppre=preorder[cnt],pos=cnt+mapp[ppre]-lef+1;
if(cnt+1<n)
{
int pos1=preorder[cnt+1];
if(mapp[pos1]>=lef&&mapp[pos1]<mapp[ppre])
{
wrk->left=new TreeNode(pos1);
dfs(wrk->left,cnt+1,lef,mapp[ppre]-1);
}
}
if(pos>=0&&pos<n&&mapp[preorder[pos]]<=rig&&mapp[preorder[pos]]>mapp[ppre])
{
wrk->right=new TreeNode(preorder[pos]);
dfs(wrk->right,pos,mapp[ppre]+1,rig);
}
return;
}
class Solution {
public:
TreeNode* buildTree(vector<int>& pre, vector<int>& ino) {
n=pre.size();
preorder=pre;
inorder=ino;
for(int i=0;i<n;i++)
mapp[inorder[i]]=i;
TreeNode* ans=NULL;
if(n)
{
ans=new TreeNode(preorder[0]);
dfs(ans,0,0,n-1);
}
return ans;
}
};