输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
程序员文章站
2024-02-21 12:24:28
...
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()!=vin.size()||pre.size()==0||vin.size()==0)
{
return NULL;
}
TreeNode *pRoot=GreateTree(pre,vin,0,0,vin.size()-1);
return pRoot;
}
TreeNode *GreateTree(vector<int> pre,vector<int> vin,int preroot,int leftR,int rightR)
{
int i,j,root;
root=pre[preroot];
if(leftR>rightR)
{
return NULL;
}
for(;i<=rightR;i++)
{
if(vin[i]==root)
{
j=i;
}
}
int leftlen=j-leftR;
TreeNode *pRoot=new TreeNode(root);
pRoot->left=GreateTree(pre,vin,preroot+1,leftR,j-1);
pRoot->right=GreateTree(pre,vin,preroot+leftlen+1,j+1,rightR);
return pRoot;
}
};