先序建立二叉树,先序输出没有问题,但是后序输出以及中序输出存在问题
#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");
}
--------------------编程问答-------------------- 先把如何调试程序学好吧
--------------------编程问答-------------------- 我以为没有发出去,所以没有写完
这是运行的结果
我输入这样的一棵树
A
B C
# D # #
E #
# #
中序为:BEDAC
后序为:EDBCA
与程序不一样,可是我觉得程序也没有错啊!!!
请赐教,谢谢!!
补充:.NET技术 , VC.NET