题目描述:给定前序和中序序列,构建一颗二叉树
节点定义为:
struct TreeNode{
int val;
TreeNode * left;
TreeNode * right;
TreeNode (int x) : val(x),left(NULL),right(NULL){}
};
很明显,可以将大问题划分成子问题,用递归实现
时间复杂度为O(N),空间复杂度为O(logN)
class Solution{
public :
TreeNode * construct(vector<int> & preorder,vector<int> & inorder){
int len = preorder.size();
if(len <= 0) return NULL;
TreeNode * ans = createTree(preorder,0,len-1,inorder,0,len-1);
return ans;
}
TreeNode * createTree(vector<int> & preorder,int prestart,int preend,vector<int> & inorder,int instart,int inend){
if(instart > inend) return NULL;
int index;
for(int i = instart;i<=inend;i++){
if(preorder[prestart] == inorder[i]){
index = i;
break;
}
}
int lenth = index-instart;
TreeNode * root = new TreeNode(preorder[prestart]);
root->left = createTree(preorder,prestart+1,prestart+lenth,inorder,instart,index-1);
root->right = createTree(preorder,prestart+lenth+1,preend,inorder,index+1,inend);
return root;
}
};