|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<iostream>
- using namespace std;
- typedef char Elemtype;
- typedef struct BiTNode{
- Elemtype data;
- struct BiTNode *lchild,*rchild;
- }BiTNode,*BiTree;
- void initTree(BiTree &T);
- void visit(BiTNode T);
- void preorderTravel(BiTree T);
- void buildTreeByPre_In(BiTree &T);
复制代码
头文件
- #include "BinaryTree.h"
- // 初始化二叉树
- void initTree(BiTree &T) {
- T = (BiTree)malloc(sizeof(BiTNode));
- T->lchild = NULL;
- T->rchild = NULL;
- }
- // 访问节点
- void visit(BiTree T) {
- cout << T->data;
- }
- // 遍历,这里实现前序遍历,要实现中序遍历,只需要将visit放到中间即可
- void preorderTravel(BiTree T) {
- if(T != NULL) {
- visit(T);
- preorderTravel(T->lchild);
- preorderTravel(T->rchild);
- }
- }
- // 通过前序和中序遍历序列构造一棵树
- void buildTreeByPre_In(BiTree &T, string preorder, string inorder,int start, int end) {
- if(start > end)
- return;
- if(T == NULL)
- T = (BiTree)malloc(sizeof(BiTNode)); // T 为空就生成节点
- T->data = preorder[start];// 构造节点
- int pos = 0;
- while(inorder[pos] != preorder[start]) // 查找根节点所在位置
- pos++;
- int count = pos - start;
- buildTreeByPre_In(T->lchild,preorder,inorder,start+1,start+count);
- buildTreeByPre_In(T->rchild,preorder,inorder,start+count+1,end);
- }
复制代码
方法定义
- #include "BinaryTree.cpp"
- int main() {
- BiTree T;
- initTree(T);
- string preorder,inorder;
- cin >> preorder;
- cin >> inorder;
- buildTreeByPre_In(T,preorder,inorder,0,preorder.length());
- preorderTravel(T);
- return 0;
- }
复制代码
主函数
这段代码是用来通过中序遍历和前序遍历生成二叉树的,可是运行的时候就是会报段错误,我不知道是哪里出了问题,调试也是自己突然就段错误了,找不到头绪 |
|