Problem1868--【查找】7-4 基于非递归的二叉排序树的结点的查找和插入

1868: 【查找】7-4 基于非递归的二叉排序树的结点的查找和插入

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 4  Solved: 1
[Submit] [Status] [Web Board] [Creator:]

Description

已知二叉树T的结点形式为(llink,data,count,rlink),在树中查找值为x的结点,若找到,则计数(count)加1;否则,作为一个新结点插入树中,插入后仍为二叉排序树。请写出其非递归算法。

Input

多组数据,每组数据3行。第一行为二叉排序树的结点数n,第二行为空格分隔的n个数字,对应二叉排序树中的n个结点,第三行为查找的值x。n=0时输入结束。

Output

每组数据输出两行。第一行为二叉排序树的中序序列(空格分隔),第二行为其对应的计数count。

Sample Input Copy

5
1 2 3 4 5
3
6
1 3 4 5 6 7
2
0

Sample Output Copy

1 2 3 4 5
 0 1 0 0
1 2 3 4 5 6 7
0 0 0 0 0 0 0

HINT

#include<iostream>
using namespace std;
typedef struct BiTNode
{
    int data;
    int cnt;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int sum=0;        //全局变量sum表示排序树当前结点的个数,也为了判断数据是否为输出的最后一个数
void SearchBST(BiTree &T,int x)
{//基于非递归的二叉排序树的结点的查找和插入
    /**************begin************/

    /**************end************/
}
void InOrderTraverse(BiTree T)
{//中序遍历输出二叉树T结点
    if(T==NULL) return;
    else
    {
        InOrderTraverse(T->lchild);
        sum--;
        cout<<T->data;
        if(sum==0)
            cout<<endl;
        else
            cout<<" ";
        InOrderTraverse(T->rchild);
    }
}
void Print_Count(BiTree T,int x)
{//中序遍历输出二叉树T计数
    if(T==NULL) return;
    else
    {
        Print_Count(T->lchild,x);
        sum--;
        cout<<T->cnt;
        if(sum==0)
            cout<<endl;
        else
            cout<<" ";
        Print_Count(T->rchild,x);
    }
}
int main()
{
    int n;
    while(cin>>n)
    {
        if(n==0) break;
        int e;        //变量e用于接收输入数据
        BiTree T=NULL;
        for(int i=0;i<n;i++)  //基于非递归的二叉排序树的结点的查找和插入
        {
            cin>>e;
            SearchBST(T,e);
        }
        int x;           //查找值为x
        cin>>x;
        SearchBST(T,x);
        if(sum==n+1) n++; //没找到时,x作为一个新结点插入树中,此时排序树的结点数加1
        sum=n;
        InOrderTraverse(T);//中序遍历输出二叉树T结点
        sum=n;
        Print_Count(T,x);   //中序遍历输出二叉树T计数
    }
    return 0;
}

Source/Category