跳到正文

剪贴板

剪贴板 qi9z0mvw

原文
剪贴板信息

剪贴板信息

收录
更新

二叉树的前中后序

C++
#include <bits/stdc++.h>
using namespace std;
int Read_int() {
	int x = 0, f = 1;
	char c = getchar();
	while(c > '9' || c < '0') {
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		x *= 10;
		x += c - '0';
		c = getchar();
	}
	return x * f;
}
long long Read_longlong() {
	long long x = 0, f = 1;
	char c = getchar();
	while(c > '9' || c < '0') {
		if(c == '-') f = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		x *= 10;
		x += c - '0';
		c = getchar();
	}
	return x * f;
}
int n, ls, rs;
struct tree{
	int lson, rson;
	node(int alson = 0, int arson = 0) {
		lson = alson, rson = arson;
	}
}T[100005];
void first_per(int father) {
	cout << father << " ";
	if(T[father].lson) first_per(T[father].lson);
	if(T[father].rson) first_per(T[father].rson);
}
void middle_per(int father) {
	if(T[father].lson) first_per(T[father].lson);
	cout << father << " ";
	if(T[father].rson) first_per(T[father].rson);
}
void last_per(int father) {
	if(T[father].lson) first_per(T[father].lson);
	if(T[father].rson) first_per(T[father].rson);
	cout << father << " ";
}
int main(void) {
	cout << "输入一个数n,表示这棵二叉树的节点数:" << endl; 
	n = Read_int();
	cout << "接下来输入n行,每行两个整数ai,bi,表示节点i的左右儿子,没有输入0(ai,bi < n):" << endl; 
	for (int i = 1; i <= n; i++) {
		T[i].lson = Read_int();
		T[i].rson = Read_int();
	}
	first_per(1);
	cout << endl;
	middle_per(1);
	cout << endl;
	last_per(1);
	return 0;
}