#include <iostream>
using namespace std;
/*
非空二叉排序树上查找元素值为e的结点,若存在返回其指针;若该结点不存在,
则插入一个元素值为e的新结点,并返回新结点的指针;
欲建树:
7
/ \
5 9
*/
typedef struct {
int key;
char info[10];
} elemtype;
typedef struct node {
elemtype data;
node *lchild, *rchild;
}node, *bitptr;
//注意理解typedef , node, *bitptr的意义;
void createTree(bitptr& T)
{
T = (node*)malloc(sizeof(node));
elemtype e1, e2, e3;
e1.key = 7;
e2.key = 5;
e3.key = 9;
T->data = e1;
node *t1 = (node*)malloc(sizeof(node));
node *t2 = (node*)malloc(sizeof(node));
t1->data = e2;
t2->data = e3;
t1->lchild = t1->rchild = NULL;
t2->lchild = t2->rchild = NULL;
T->lchild = t1;
T->rchild = t2;
}
node* Search_Insert(bitptr& T, elemtype e)//如果后续不需要遍历打印树,这里可以把bitptr& T写成bitptr T;
{
if (T == NULL)
{
//不存在元素值为e的结点
T = (node*)malloc(sizeof(node));
T->data = e;
T->lchild = T->rchild = NULL;
return T;
}
if (e.key == T->data.key)
return T;
if (e.key < T->data.key)
Search_Insert(T->lchild, e);
else
Search_Insert(T->rchild, e);
}
void printtree(bitptr T)
{
if (T == NULL)
return;
cout << T->data.key << endl;
printtree(T->lchild);
printtree(T->rchild);
}
int main()
{
bitptr T;
createTree(T);
elemtype e;
e.key = 4;
cout << "插入前:" << endl;
printtree(T);
bitptr q = Search_Insert(T, e);
cout << "插入了:" << q->data.key << endl;
cout << "插入后:" << endl;
printtree(T);
return 0;
}
输出: