Invert a Binary Tree

#include<bits/stdc++.h>
using namespace std;

const int Max=50;
int n,num;
bool notroot[Max];

struct Node {
	int lchild,rchild;
} node[Max];

void print(int id){
	printf("%d",id);
	num++;
	if(num<n) printf(" ");
	else printf("\n");
}

void postorder(int root) {
	if(root==-1) {
		return ;
	}
	postorder(node[root].lchild);
	postorder(node[root].rchild);
	swap(node[root].lchild,node[root].rchild);
}

void BFS(int root){
	queue<int> q;
	q.emplace(root);
	while(!q.empty()){
		int now=q.front();
		q.pop();
		print(now);
		if(node[now].lchild!=-1) q.emplace(node[now].lchild);
		if(node[now].rchild!=-1) q.emplace(node[now].rchild);
	}
}

void inorder(int root){
	if(root==-1){
		return ;
	}
	inorder(node[root].lchild);
	print(root);
	inorder(node[root].rchild);
}

int strTonum(char c) {
	if(c=='-') {
		return -1;
	} else {
		notroot[c-'0']=1;
		return c-'0';
	}
}

int Find() {
	for(int i=0; i<n; i++) {
		if(!notroot[i]) {
			return i;
		}
	}
}

int main() {
	scanf("%d",&n);
	char a,b;
	for(int i=0; i<n; i++) {
		scanf("%*c%c %c",&a,&b);
		node[i].lchild=strTonum(a);
		node[i].rchild=strTonum(b);
	}
	int root=Find();
	postorder(root);
	BFS(root);
	num=0;
	inorder(root);
	return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务