先序建立二叉树,先序输出没有问题,但是后序输出以及中序输出存在问题

x397496544 2013-05-16 04:45:30
#include <iostream>
using namespace std;

typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void CreatebiTree(BiTree &T){
// 在先序遍历二叉树过程中输入结点字符,建立二叉链表存储结构,
// 指针T指向所建二叉树的根结点
char ch;
cin >> ch ;
if (ch=='#') T=NULL; // 建空树
else {
T = new BiTNode ; // "访问"操作为生成根结点
T->data = ch;
CreatebiTree(T->lchild); // 递归建(遍历)左子树
CreatebiTree(T->rchild); // 递归建(遍历)右子树
}//else
}//CreateBiTree

void Preorder (BiTree T){
// 先序遍历以T为根指针的二叉树
if (T!=NULL) {
cout<<T->data ;
Preorder(T->lchild); // 先序遍历左子树
Preorder(T->rchild); // 先序遍历右子树
}
}

void Inorder (BiTree T){
if (T!=NULL) {
Preorder(T->lchild);
cout<<T->data ;
Preorder(T->rchild);
}
}

void Postorder (BiTree T){
if (T!=NULL) {
Preorder(T->lchild);
Preorder(T->rchild);
cout<<T->data ;
}
}


void BiTreeDepth(BiTree T, int h, int &depth){
// h为T指向的结点所在层次,T指向二叉树的根,则h的初值为1,
// depth为当前求得的最大层次,其初值为0
if (T){
if (h>depth) depth=h;
BiTreeDepth(T->lchild, h+1, depth);
BiTreeDepth(T->rchild, h+1, depth);
}
}//BiTreeDepth

BiTNode *GetTreeNode(char item,BiTNode *lptr,BiTNode *rptr){
BiTNode *T;
T=new BiTNode;
T->data=item;
T->lchild=lptr;
T->rchild=rptr;
return T;
}//GetTreeNode

BiTNode *CopyTree(BiTNode *T){
// 已知二叉树的根指针为T,本算法返回它的复制品的根指针
BiTNode *newlptr;
BiTNode *newrptr;
BiTNode *newnode;
if (!T )
return NULL; // 复制一棵空树
if (T->lchild )
newlptr = CopyTree(T->lchild); // 复制(遍历)左子树
else newlptr = NULL;
if (T->rchild )
newrptr = CopyTree(T->rchild); // 复制(遍历)右子树
else newrptr = NULL;
newnode = GetTreeNode(T->data, newlptr, newrptr); // 生成根结点
return newnode;
}


void main(){
int depth;
BiTree T,S;
cout<<"先序遍历创建二叉树:";
CreatebiTree(T);
cout<<"先序遍历二叉树";
Preorder(T);
cout<<endl;
cout<<"中序序遍历二叉树";
Inorder(T);
cout<<endl;
cout<<"后序遍历二叉树";
Postorder(T);
cout<<endl;
cout<<"二叉树的深度:";
BiTreeDepth(T,1,depth);
cout<<depth;
cout<<endl;
cout<<"复制二叉树"<<endl;
S=CopyTree(T);
Preorder(S);
system("pause");
}




...全文
379 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
x397496544 2013-06-05
  • 打赏
  • 举报
回复
我以为没有发出去,所以没有写完 这是运行的结果 我输入这样的一棵树 A B C # D # # E # # # 中序为:BEDAC 后序为:EDBCA 与程序不一样,可是我觉得程序也没有错啊!!! 请赐教,谢谢!!
真相重于对错 2013-05-16
  • 打赏
  • 举报
回复
先把如何调试程序学好吧

7,540

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 VC.NET
社区管理员
  • VC.NET社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧