赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
二叉树bt:A(B(D,E(G,H)),C(,F(I)))
构造先序线索二叉树tb
A B D E G H C F I
输出逆先序二叉树tb
I F C H G E D B A
- #include <stdio.h>
- #include <malloc.h>
- #define MaxSize 100
- typedef char ElemType;
- typedef struct tnode
- {
- ElemType data; //数据域
- struct tnode* lchild, * rchild; //指针域
- } BTNode;
-
- void CreateBTree(BTNode*& bt, char* str)
- {
- BTNode* St[MaxSize], * p = NULL;
- int top = -1, k, j = 0;
- char ch;
- bt = NULL; //建立的二叉树初始时为空
- ch = str[j];
- while (ch != '\0') //str未扫描完时循环
- {
- switch (ch)
- {
- case '(':top++; St[top] = p; k = 1; break; //为左孩子结点
- case ')':top--; break;
- case ',':k = 2; break; //为右孩子结点
- default:p = (BTNode*)malloc(sizeof(BTNode));
- p->data = ch; p->lchild = p->rchild = NULL;
- if (bt == NULL) //*p为二叉树的根结点
- bt = p;
- else //已建立二叉树根结点
- {
- switch (k)
- {
- case 1:St[top]->lchild = p; break;
- case 2:St[top]->rchild = p; break;
- }
- }
- }
- j++;
- ch = str[j];
- }
- }
- void PreOrder(BTNode* bt)
- {
- if (bt != NULL)
- {
- printf("%c ", bt->data);
- PreOrder(bt->lchild);
- PreOrder(bt->rchild);
- }
- }
- void PreOrder1(BTNode* bt) // 逆先序遍历
- {
- if (bt != NULL)
- {
- PreOrder1(bt->rchild);
- PreOrder1(bt->lchild);
- printf("%c ", bt->data);
- }
- }
-
- void DestroyBTree(BTNode*& bt)
- {
- if (bt != NULL)
- {
- DestroyBTree(bt->lchild);
- DestroyBTree(bt->rchild);
- free(bt);
- }
- }
-
- void DispBTree(BTNode* bt)
- {
- if (bt != NULL)
- {
- printf("%c", bt->data);
- if (bt->lchild != NULL || bt->rchild != NULL)
- {
- printf("("); //有子树时输入'('
- DispBTree(bt->lchild); //递归处理左子树
- if (bt->rchild != NULL) //有右子树时输入'.'
- printf(",");
- DispBTree(bt->rchild); //递归处理右子树
- printf(")"); //子树输出完毕,再输入一个')'
- }
- }
- }
- int main()
- {
- BTNode* bt;
- char str[] = "A(B(D,E(G,H)),C(,F(I)))";
- CreateBTree(bt, str);
- printf("二叉树bt:"); DispBTree(bt); printf("\n");
- printf("构造先序线索二叉树tb\n");
- PreOrder(bt);
- printf("\n");
- printf("输出逆先序二叉树tb\n");
- PreOrder1(bt);
- printf("\n");
- return 0;
-
- }
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了二叉树广义表的使用,提供了大量能使我们快速便捷地处理数据的函数和方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。