码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树先序构建+(先序,中序,后序遍历)

时间:2014-12-04 18:10:28      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   os   sp   on   2014   log   ef   

/*
 * 样例     DBA,,C,,E,GF,,,
 */
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#define ms(x,y) memset(x,y,sizeof(x))
const int MAXN=1000+10;
const int INF=1<<30;
using namespace std;

struct Node
{
	char ch;
	Node *left, *right;
};

void BuildTree(Node *&root)
{
	Node *s = (Node *)malloc(sizeof(Node));
	s->left = NULL;
	s->right = NULL;
	scanf("%c", &s->ch);
	if(s->ch == ','){
		free(s);
		return;
	}
	root = s;
	BuildTree(root->left);
	BuildTree(root->right);
}

void PreOrder(Node *root)
{
	if(root == NULL) return;
	printf("%c", root->ch);
	PreOrder(root->left);
	PreOrder(root->right);
}

void InOrder(Node *root)
{
	if(root == NULL) return;
	InOrder(root->left);
	printf("%c", root->ch);
	InOrder(root->right);
}

void PostOrder(Node *root)
{
	if(root == NULL) return;
	PostOrder(root->left);
	PostOrder(root->right);
	printf("%c", root->ch);
}

int main()
{
	freopen("in.txt","r",stdin);

	Node *root;
	BuildTree(root);

	PreOrder(root);
	printf("\n");

	InOrder(root);
	printf("\n");
	
	PostOrder(root);
	printf("\n");

	return 0;
}

二叉树先序构建+(先序,中序,后序遍历)

标签:blog   io   ar   os   sp   on   2014   log   ef   

原文地址:http://blog.csdn.net/u013351484/article/details/41725495

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!