1102 Invert a Binary Tree

25 篇文章 0 订阅
11 篇文章 0 订阅

小知识

在 scanf 和 printf 里效果是不一样的。

在printf,动态控制显示格式用的

printf("%*s",5,“123”);
执行一下,这条语句,输出
##123

(#代表一个空格)
类似于%5d 这样的状况
这里被常量5代替,用于控制最小字符宽度,主要是针对,最小字符宽度未知的情况,当然可以对应整型变量

在 scanf 里的意思,表示忽略要读的项。比如 %*d 就是读一个 %d 该读的东西,但不赋值给任何变量。

scanf("%*d %*d %d", &n);
如果输入2004 2005 2006
那么n=2006


#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
const int maxn = 110;
struct BTnode {
	int lchild, rchild;
}node[maxn];
bool notRoot[maxn] = { false };
int n, num = 0;
void print(int id) {
	printf("%d", id);
	num++;
	if (num < n)	printf(" ");
	else printf("\n");
}
void inorder(int root) {
	if (root == -1)	return;
	inorder(node[root].lchild);
	print(root);
	inorder(node[root].rchild);
}
void BFS(int root) {
	queue<int> q;
	q.push(root);
	while (!q.empty()) {
		int now = q.front();
		q.pop();
		print(now);
		if (node[now].lchild != -1)	q.push(node[now].lchild);
		if (node[now].rchild != -1)	q.push(node[now].rchild);
	}
}
void postorder(int root) {
	if (root == -1)	return;
	postorder(node[root].lchild);
	postorder(node[root].rchild);
	swap(node[root].lchild, node[root].rchild);
}
int strTonum(char c) {
	if (c == '-')	return -1;
	else {
		notRoot[c - '0'] = 1;
		return c - '0';
	}
}
int findRoot() {
	for (int i = 0; i < n; i++) {
		if (notRoot[i] == 0)	return i;
	}
}
int main() {
	char lchild, rchild;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {//关键是怎么处理输入,到node里面
		scanf("%*c%c %c", &lchild, &rchild);//%*c吃掉一个回车
		node[i].lchild = strTonum(lchild);
		node[i].rchild = strTonum(rchild);
	}
	int root = findRoot();
	postorder(root);//后序反转二叉树
	BFS(root);
	num = 0;
	inorder(root);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值