您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树二:遍历二叉树

2016-10-28 16:08 274 查看

SDUT原题:点击打开链接

中序遍历:顾名思义就是先访问左子树,再访问根,最后访问右子树
后续遍历:先访问左子树,在访问右子树,最后访问根
这个序就是按照根的节点来排序的
#include <iostream>
#include <stdlib.h>
using namespace std;

char ch[100];
int cnt;
struct node
{
char data;
struct node * lchild;
struct node * rchild;
};

struct node * creat()
{
struct node * root;
if(ch[++cnt] == ',')
root = NULL;
else
{
root = (struct node * )malloc(sizeof(struct node));
root->data = ch[cnt];
root->lchild = creat();
root->rchild = creat();
}
return root;
};

void zhongxu(struct node * root)
{
if(root)
{
zhongxu(root->lchild);
cout << root->data;
zhongxu(root->rchild);
}
}

void houxu(struct node * root)
{
if(root)
{
houxu(root->lchild);
houxu(root->rchild);
cout << root->data;
}
}

int main()
{
struct node * root;
while(cin >> ch)
{
cnt = -1;
root = creat();
zhongxu(root);
cout << endl;
houxu(root);
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: