非递归二叉排序树

江枫思渺然 提交于 2019-12-05 10:04:33
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>//非递归
using namespace std;
int a[1000];
int q = 0;
int flag = 0;
typedef struct BiTNode {
    int data;
    struct BiTNode *lchild, *rchild;
    int count;
}BiTNode,*BiTree;
void InsertBST(BiTree &T,int e)
{
    BiTNode *cur=T;
    BiTree s = new BiTNode;
    s->data = e;
    s->count = 0;
    s->lchild = NULL;
    s->rchild = NULL;
    if (!T)
    {

        T = s;
    }
    else
    {
        BiTNode *parent=T;
        while (cur != NULL)
        {
            parent = cur;
            if (e > parent->data)
                cur = parent->rchild;
            else
                if (e < parent->data)
                    cur = parent->lchild;
                else
                    if (e == parent->data)
                    {
                        parent->count++;
                        flag = 1;
                        break;
                    }
        }
        if (e > parent->data)
            parent->rchild = s;
        if (e < parent->data)
            parent->lchild = s;
    }
}
void CreatBST(BiTree &T,int n,int V[])
{
    T = NULL;
    for (int i = 0; i < n; i++)
    {
        InsertBST(T, V[i]);
    }
}
int s[1000];
int i = 0;
void InorderTraverse(BiTree T,int e)
{
    if (T != NULL)
    {
        
        InorderTraverse(T->lchild,e);
        if (T->data != e)
        {
            cout << " " << T->data;
            s[i] = T->count;
            i++;
        }
        InorderTraverse(T->rchild,e);
    }
}
int main()
{
    int n;
    while (cin >> n && n != 0)
    {
        q = 0;
        BiTree T;
        int V[1000];
        flag = 0;
        for (int i = 0; i < 100; i++)
            s[i] = 0;
        for (int i = 0; i < n; i++)
        {
            cin >> V[i];
        }
        CreatBST(T, n, V);
        int a;
        cin >> a;
        InsertBST(T, a);
        BiTree p;
        p = T;
        while (p->lchild)
        {
            p = p->lchild;
        }
        cout << p->data;
        s[0] = p->count;
        i++;
        int e = p->data;
        InorderTraverse(T,e);
        cout << endl;
        int m=0;
        if (flag == 0)
            m = n + 1;
        else
            m = n;
        cout << s[0];
        for (int i = 1; i < m; i++)
        {
            cout << " " << s[i];
        }
        cout << endl;
    }
    return 0;
}

1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!