PTA 7-2 二叉树的遍历DFS

根据输入构造二叉树,输出该二叉树的先序序列。二叉树共有N个节点,节点编号是1到N。约定1号节点是根节点。
输入格式:

第一行输入整数N。 接下来有N行,依次给出1到N节点的左孩子和右孩子。对于这N行中的每一行,有两个整数。第i(i=1, 2, …, N)行中,第一个整数指出左孩子的编号,第二个整数指出右孩子的编号。如果整数值为0,表示没有左孩子或右孩子。
输出格式:

输出一行,内容是二叉树的先序序列。节点编号之间用空格隔开,行末有1个空格。
输入样例:

6
2 5
3 4
0 0
0 0
0 6
0 0

输出样例:

1 2 3 4 5 6 

代码如下

#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

	char print_f[105];
	void read() {}
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T, typename... T2>
		inline void print(T x, T2... oth) {
			ll p3=-1;
			if(x<0) putchar('-'), x=-x;
			do{
				print_f[++p3] = x%10 + 48;
			} while(x/=10);
			while(p3>=0) putchar(print_f[p3--]);
			putchar(' ');
			print(oth...);
		}
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K, tot;

struct Node {
	int lef, rig;
} tree[MAXN<<2];

void dfs(int u) {
	printf("%d ", u);
	if(tree[u].lef) dfs(tree[u].lef);
	if(tree[u].rig) dfs(tree[u].rig);
}

int main() {
#ifdef debug
	freopen("test", "r", stdin);
	clock_t stime = clock();
#endif
	read(n);
	for(int i=1; i<=n; i++) 
		read(tree[i].lef, tree[i].rig);
	dfs(1);




#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}




全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务