九度oj 1184 二叉树遍历

本文介绍了一个简单的C++程序,用于构建和遍历二叉树。通过输入字符串序列,程序能够创建二叉树并进行前序遍历,最后输出遍历结果。

原题链接:http://ac.jobdu.com/problem.php?pid=1184

水题,纯当练手,第一个c++程序O(∩_∩)O~~。。。

具体如下:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
struct node{
	char key;
	node *ch[2];
	node(char d) : key(d) { ch[0] = ch[1] = NULL; }
}*root = NULL;
int n = 0;
static int k = -1;
char buf[110];
void built(node *&p){
	k++;
	if (k > n) return;
	if (buf[k] != '#'){
		p = new node(buf[k]);
		built(p->ch[0]);
		built(p->ch[1]);
	}
}
void travle(node *x){
	if (x != NULL){
		travle(x->ch[0]);
		printf("%c ", x->key);
		travle(x->ch[1]);
	}
}
void _free(node *x){
	if (x != NULL){
		_free(x->ch[0]);
		_free(x->ch[1]);
		delete x;
	}
}
int main(){
#ifdef LOCAL
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w+", stdout);
#endif
	while (~scanf("%s", buf)){
		k = -1, root = NULL, n = strlen(buf);
		built(root);
		travle(root);
		_free(root);
		printf("\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值