1102 Invert a Binary Tree(25 分)

静态树存储,找一下根节点,遍历的时候左右节点换一下就可以了

算法笔记上给的方法是:后序遍历时交换左右子树,重建二叉树,再进行遍历

#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
int n;
const int maxn = 20;
struct node {
	int lchild, rchild;
}Node[maxn];
bool root[maxn];
vector<int>layer, in;
int convert(char c)
{
	if (c == '-')return -1;
	else return c - '0';
}
void layerorder(int head)
{
	queue<int>q;
	q.push(head);
	while (!q.empty())
	{
		int top = q.front();
		q.pop();
		layer.push_back(top);
		if (Node[top].rchild != -1)q.push(Node[top].rchild);
		if (Node[top].lchild != -1)q.push(Node[top].lchild);
	}
}
void inorder(int head)
{
	if (head == -1)return;
	inorder(Node[head].rchild);
	in.push_back(head);
	inorder(Node[head].lchild);
}
void showarr(vector<int>a)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d", a[i]);
		if (i != n - 1)printf(" ");
		else printf("\n");
	}
}
int main()
{
	scanf("%d", &n);
	for(int i=0;i<n;i++)
	{
		getchar();
		char a, b;
		scanf("%c %c", &a, &b);
		Node[i].lchild = convert(a);
		Node[i].rchild = convert(b);
		if (Node[i].lchild >= 0)root[Node[i].lchild] = true;
		if (Node[i].rchild >= 0)root[Node[i].rchild] = true;
	}
	int head;
	for (head=0;head<n;head++)
	{
		if (root[head] == false)break;
	}
	layerorder(head);
	inorder(head);
	showarr(layer);
	showarr(in);
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值