文章目录
//根据先序和中序构建二叉树,然后按层打印每个节点,队列
#include  <iostream>
#include<queue>
#include<exception>
using namespace std;
struct BinaryTreeNode{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};

BinaryTreeNode* ContrustCore(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder){
    //根据先序确定第一个数值确定根节点
   //BinaryTreeNode *root;
    int rootValue=startpreorder[0];
    BinaryTreeNode* root=new BinaryTreeNode();//为链表申请空间
    root->m_nValue=rootValue;
    root->m_pLeft=root->m_pRight=NULL;
    if(startpreorder==endpreorder){
        if(startinorder==endinorder && *startpreorder==*endpreorder)//z只有一个根节点
            return root;
        else
            throw std::exception();
    }
    //在中序找到根节点所在位置
    int*rootinoder=startinorder;
     while(rootinoder<=endinorder && *rootinoder!=rootValue)
        rootinoder++;
     if(rootinoder==endinorder && *rootinoder!=rootValue)//在中序中没有找到根节点
         throw exception();
     int leftLength=rootinoder-startinorder;
     int* leftPreorderEnd=startpreorder+leftLength;
     if(leftLength>0)//左子树的长度,构建左子树
     {
         root->m_pLeft=ContrustCore(startpreorder+1,leftPreorderEnd,startinorder,rootinoder-1);
     }
    if(leftLength<endpreorder-startpreorder)//存在右子树
        root->m_pRight=ContrustCore(leftPreorderEnd+1,endpreorder,rootinoder+1,endinorder);
    return root;
}
BinaryTreeNode* Contrust(int* preorder,int* inorder,int length){
        if(preorder==NULL||inorder==NULL||length<=0)
            return NULL;
        return ContrustCore(preorder,preorder+length-1,inorder,inorder+length-1);
}
void PrintFromTopToBottom(BinaryTreeNode* pTreeRoot){
    if(!pTreeRoot)
        return;
    queue<BinaryTreeNode*> que;
    que.push(pTreeRoot);
    while(que.size()){
        BinaryTreeNode* pNode=que.front();//指向队列的第一个元素,要被弹出的元素
        que.pop();
        cout<<pNode->m_nValue<<" ";
        if(pNode->m_pLeft)//打印节点的左右子节点
            que.push(pNode->m_pLeft);
        if(pNode->m_pRight)
            que.push(pNode->m_pRight);
    }
}
int main(){
    BinaryTreeNode* Btree;
    int preorder[]={8,6,5,7,10,9,11};
    int inorder[]={5,6,7,8,9,10,11};
    Btree= Contrust(preorder,inorder,7);
    PrintFromTopToBottom(Btree);
    return 0;
}
文章目录