前序中序建立二叉树

#include<iostream>
using namespace std;

struct BinaryTreeNode{
    char data;
    BinaryTreeNode* leftChild;
    BinaryTreeNode* rightChild;
    BinaryTreeNode(char newdata):data(newdata){}
};
BinaryTreeNode* createBinaryTree(char* VLR,char* LVR,int n){
    if(n==0){
        return NULL;
    }
    int k=0;
    while(VLR[0]!=LVR[k]){
        k++;
    }
    BinaryTreeNode* p=new BinaryTreeNode(VLR[0]);
    p->leftChild=createBinaryTree(VLR+1,LVR,k);
    p->rightChild=createBinaryTree(VLR+k+1,LVR+k+1,n-k-1);
    return p;
}
void last(BinaryTreeNode* root){
    if(root!=NULL){
        last(root->leftChild);
        last(root->rightChild);
        cout<<root->data;
    }
}
int main(){
    char* vlr = "ABCDEFGH";//前序
    char* lvr = "CBEDFAGH";//中序
    BinaryTreeNode* treeRoot;
    treeRoot=createBinaryTree(vlr,lvr,8);//根据前序和中序序列创建二叉树,并返回根节点指针
    cout<<"后序遍历序列:";
    last(treeRoot);//目标输出应为:CEFDBHGA
    cout<<endl;
    return 0;
}

 

posted @ 2020-07-28 18:03  执着于风  Views(572)  Comments(0)    收藏  举报