二叉树的中序输出

来源:互联网 发布:lol主播的淘宝店网址 编辑:程序博客网 时间:2024/06/05 12:57
// createBiTree.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <stack>#include <iostream>using namespace std;//定义二叉树的结构typedef struct BiTNode{char data;struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;//创建二叉树//使用递归调用的方式bool CreateBiTree(BiTree &T){char ch;cin>>ch;if (ch == '#') T=0;  //将指针赋值为空else{if (!(T = (BiTNode *)malloc(sizeof(BiTNode)))) return 1;T->data = ch;CreateBiTree(T->lchild);//递归创建左子树CreateBiTree(T->rchild);//递归创建右子树}return 0;}//CreateBiTreebool InOrderTraverse(BiTree T){//采用二叉链表存储结构//中序遍历二叉树T的非递归算法,对每个数据元素进行输出stack<BiTree> S;BiTNode *p=T;while (p || !S.empty()){if (p) {S.push(p);p = p->lchild;}        else {p=S.top();cout<<p->data<<endl;p=p->rchild;S.pop();}}//whilereturn 0;}int main(int argc, char* argv[]){BiTree testree;if(CreateBiTree(testree))cout<<"二叉树没有创建成功"<<endl; //二叉树没有创建成功if(!InOrderTraverse(testree))return 1;                             //没有遍历成功return 0;}

原创粉丝点击