A1102 Invert a Binary Tree [反转二叉树/镜像]

在这里插入图片描述
给一棵二叉树子节点下标,要求反转二叉树,之后按要求输出层序和中序遍历。
思路:因为是给的子节点下标,用二叉树的静态写法会更加方便,找出根节点后,按照后序遍历反转二叉树(交换左右子树),然后再按照模板层序中序遍历输出

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 110;
struct node
{
	int lchild, rchild;
}Node[maxn];
bool notroot[maxn] = { false };
int n, num = 0;
void print(int id)
{
	cout << id;
	num++;
	if (num < n)
		cout << " ";
	else
		cout << endl;
}
void bfs(int root)
{
	queue<int>q;
	q.push(root);
	while (!q.empty())
	{
		int temp = q.front();
		q.pop();
		print(temp);
		if (Node[temp].lchild != -1)
			q.push(Node[temp].lchild);
		if (Node[temp].rchild != -1)
			q.push(Node[temp].rchild);
	}
}
void inorder(int root)
{
	if (root == -1)
		return;
	inorder(Node[root].lchild);
	print(root);
	inorder(Node[root].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'] = true;
		return c - '0';
	}
}
int findroot()
{
	for (int i = 0; i < n; i++)
	{
		if (notroot[i] == false)
			return i;
	}
}
int main()
{
	char lchild, rchild;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> lchild >> rchild;
		Node[i].lchild = strTonum(lchild);
		Node[i].rchild = strTonum(rchild);
	}
	int root = findroot();
	postorder(root);
	bfs(root);
	num = 0;
	inorder(root);
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812017.html