二叉樹筆記建樹代碼

層序:每層從左向右讀
前序:根左右
中序:左根右
後序:左右根


struct tree
{
    int data;
    tree *lson,*rson;
};

tree *buildtree(tree *bt)
{
    int x;
    cin >> x;
    if (x == 0)
    {
        bt = NULL;
     }
    else
    { 
        bt = new tree;
        bt->data = x;
        bt->lson = buildtree (bt->lson);
        bt->rson = buildtree (bt->rson);
    }
    return bt;
}

void show (tree *bt)   //前序輸出
{
    if (bt == NULL)
    {
        return;
    }
    else
   {
        cout << bt->data << "-";    //輸出根
        show (bt->lson);
        show (bt->rson);
    }
}

void show (tree *bt)     //中序輸出
{
    if (bt == NULL)
    {
        return;
    }
    else
   {
        show (bt->lson);
        cout << bt->data << " ";    //輸出根
        show (bt->rson);
    }
}

void show (tree *bt)     //後序輸出
{
    if (bt == NULL)
    {
        return;
    }
    else
   {
        show (bt->lson);
        show (bt->rson);
        cout << bt->data << " ";    //輸出根
    }
}

void show (tree *bt)     //層序輸出
{
    tree *temp;
    if (bt == NULL)
    {
        return;
    }
    queue<tree*>Q;
    Q.push (bt);
    while (!Q.empty ())
   {
        temp = Q.front();
        Q.pop();
        cout << temp->data << " ";
        if (temp->lson != NULL)
        {
             Q.push (temp->lson);
        }
        if (temp->rson != NULL)
        {
             Q.push (temp->rson);
        }
    }
}

int main()
{
    tree *root;
    root = new tree;
    root = buildtree(root);
    show(root);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章