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

来源:互联网 发布:毛利率算法 编辑:程序博客网 时间:2024/05/23 22:37

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;}


0 0
原创粉丝点击