***主要应用递归思想建立并遍历输出二叉树
##主函数及声明定义
1 #include<iostream> 2 using namespace std; 3 4 typedef struct tnode{ 5 struct tnode *lchild; //左孩子 6 int data; 7 struct tnode *rchild; //右孩子 8 }BTNode; 9 typedef BTNode *ListBTNode; 10 ListBTNode CreateBTree(); 11 void PreOrder(ListBTNode T); 12 void INOrder(ListBTNode T); 13 void PostOrder(ListBTNode T); 14 int main() 15 { 16 ListBTNode T; 17 T=CreateBTree(); 18 cout<<"先序遍历结果:"; 19 PreOrder(T); 20 cout<<endl; 21 cout<<"中序遍历结果:"; 22 INOrder(T); 23 cout<<endl; 24 cout<<"后序遍历结果:"; 25 PostOrder(T); 26 cout<<endl; 27 }
#1二叉树的建立
ListBTNode CreateBTree() { int Data; ListBTNode T; cin>>Data; if(Data==0)//创建空树 { T=NULL; return T; } else { T=new BTNode;//申请节点内存空间 T->data=Data;// 存入数据 T->lchild=CreateBTree();//创建左子树 T->lchild=CreateBTree();//创建右子树 return T; } }
#2二叉树的遍历
- 前序遍历
void PreOrder(ListBTNode T) { if(T!=NULL) { cout<<T->data<<" "; PreOrder(T->lchild); PreOrder(T->rchild); } }
- 中序遍历
void INOrder(ListBTNode T) { if(T!=NULL) { PreOrder(T->lchild); cout<<T->data<<" "; PreOrder(T->rchild); } }
- 后序遍历
void PostOrder(ListBTNode T) { if(T!=NULL) { PreOrder(T->lchild); PreOrder(T->rchild); cout<<T->data<<" "; } }
#3运行结果截图
- 我并没有运行成功然后我也没找到原因。
- 我是先序建立一个二叉树,以截图中的为例子那么建立的二叉树应为
- 所以输出结果应为:前序:1 2 3 4 5中序:3 2 4 1 5后序:3 4 2 5 1
- 调试时出现的问题:再先序遍历函数时下一步执行错误,无法继续执行。