数据结构二叉树例题总结
二叉树的基本操作
构造
递归方法:
BiNode* BiTree::Creat(BiNode* bt)
{
char ch;
cout << "请输入节点值(以#作为空符)" << endl;
cin >> ch;
if (ch == '#') return NULL;
else
{
bt = new BiNode;
bt->data = ch;
bt->lchild=Creat(bt->lchild); //递归建立左子树
bt->rchild=Creat(bt->rchild); //递归建立右子树
}
return bt;
}
非递归方法:(非重点)
Tree::Tree( )
{
TNode *Q[Max] = {
NULL};
char ch1 = '#', ch2 = '#';
int front = -1, rear = -1;
TNode *p = NULL, *q = NULL;
cout<<"请输入根结点:";
cin>>ch1;
p = new TNode; p->data = ch1;
p->firstchild = p->rightsib = NULL;
root = p;
Q[++rear] = p;
cout<<"请输入结点对,以空格分隔:";
fflush(stdin);
ch1 = getchar(); getchar(); ch2 = getchar();
while (ch1 != '#' || ch2 != '#')
{
p = new TNode; p->data = ch2;
p->firstchild = p->rightsib = NULL;
Q