二叉树(创建,遍历) c++版

#include<iostream>
#include<queue>
using namespace std;
struct BTreeNode{
    int m_data;
    BTreeNode* m_pLeft;
    BTreeNode* m_pRight;
};

// 使用前序和中序遍历创建唯一确定二叉树
//preOrder 前序遍历序列
//inOrder 中序遍历序列
//nLen 总的节点数
/*
    1.判断所输入的序列是否符合要求
    2.取出rootdata, 创建根节点,判断只有一个节点的情况
    3.在中序序列中找到root节点,算出左子树节点数, 如果没找到root报错
    4.构建左子树, 构建右子树
*/
BTreeNode* construct(int* preOrder, int* inOrder, int nLen)
{
    if(preOrder==NULL || inOrder==NULL || nLen<=0)
    {
        return NULL;
    }
    int rootdata = preOrder[0];
    BTreeNode* root = new BTreeNode;
    root->m_data = rootdata;
    root->m_pLeft = root->m_pRight = NULL;
    if(nLen==1 && *preOrder == *inOrder)
        return root;
    //中序遍历部分
    int* rmo = inOrder;
    int nLeft = 0;
    while(*rmo != rootdata && rmo <= (inOrder+nLen -1))
    {
        ++rmo;
        ++nLeft;
    }
    if(*rmo!=rootdata)
    {
        return NULL;
    }
    if(nLeft>0)
        root->m_pLeft = construct(preOrder+1, inOrder, nLeft);
    if(nLen-nLeft-1>0)
        root->m_pRight = construct(preOrder+nLeft+1, rmo+1, nLen-nLeft-1);
    return root;
}

//先序遍历
void preOrder(BTreeNode* root)
{   
   
    if(root==NULL)
        return;
    cout<<"-"<<root->m_data;
    preOrder(root->m_pLeft);
    preOrder(root->m_pRight);
}
//中序遍历
void inOrder(BTreeNode* root)
{
    
    if(root==NULL)
        return;
    inOrder(root->m_pLeft);
    cout<<"-"<<root->m_data;
    inOrder(root->m_pRight);
}
//后序遍历
void postOrder(BTreeNode* root)
{
    
    if(root==NULL)
        return;
    postOrder(root->m_pLeft);
    postOrder(root->m_pRight);
    cout<<"-"<<root->m_data;
}
//广度优先
void breadthTravel(BTreeNode* root)
{
    if(root==NULL)
        return;
    queue<BTreeNode*> q;
    q.push(root);
    while(!q.empty())
    {
        BTreeNode* r = q.front();
        cout<<" "<<r->m_data;
        q.pop();
        if(r->m_pLeft)
            q.push(r->m_pLeft);
        if(r->m_pRight)
            q.push(r->m_pRight);
    }

}



int main()
{
    int pOrder[8]={1,2,4,7,3,5,6,8};
    //中根序列
    int iOrder[8]={4,7,2,1,5,3,8,6};
    //建树
    BTreeNode* root=construct(pOrder,iOrder,8);
    cout<<"******************"<<endl;
    cout<<"******************"<<endl;
    cout<<"先序遍历"<<endl;
    preOrder(root);
    cout<<"中序遍历"<<endl;
    inOrder(root);
    cout<<"后序遍历"<<endl;
    postOrder(root);
    cout<<"广度优先"<<endl;
    breadthTravel(root);
    return 0;
}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页