常见的根据前序遍历和中序遍历构造二叉树
根据前序遍历可以知道根节点。找到这个数字在中序遍历中出现的位置,这个数字便是这颗子树的根,这个位置之前的在根的左边,这个位置之后的在根的右边。
class Solution {
TreeNode *build(vector<int> &pre, vector<int> &in, int s,int e,int &p)
{
if(s>e)
return NULL;
int dir=-1;
for(int i=s;i<=e;i++)
if(in[i]==pre[p])
dir=i;
//system("pause");
TreeNode *t=new TreeNode(pre[p++]);
t->left=build(pre,in,s,dir-1,p);
t->right=build(pre,in,dir+1,e,p);
return t;
}
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int p =0;
return build(preorder,inorder,0, inorder.size()-1,p);
}
};