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

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

2016-07-22 11:08 399 查看
点击打开题目链接

#include <bits/stdc++.h>
using namespace std;

struct node
{
char data;
node *right, *left;
};

int i;
char str[60];
node *creat();
//void preorder(node *root);前序遍历
void Inorder(node *root);//中序遍历
void Postorder(node *root);//后序遍历

int main()
{
while(~scanf("%s", str))
{
i = 0;
node *root = creat();
//preorder(root);
//cout << endl;
Inorder(root);
cout << endl;
Postorder(root);
cout << endl;
}
return 0;
}

node *creat()
{
node *tail;
if(str[i] == ',')
{
tail = NULL;
i++;
}
else
{
tail = new node;
tail -> data = str[i];
i++;
tail -> left = creat();
tail -> right = creat();
}
return tail;
}

/*void preorder(node *root)
{
if(root)
{
cout << root -> data;
preorder(root -> left);
preorder(root -> right);
}
}*/

void Inorder(node *root)
{
if(root)
{
Inorder(root -> left);
cout << root -> data;
Inorder(root -> right);
}
}

void Postorder(node *root)
{
if(root)
{
Postorder(root -> left);
Postorder(root -> right);
cout << root -> data;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树