【PAT甲级】1102 Invert a Binary Tree (25分)

解题过程的小记录,如有错误欢迎指出。

难度:三星(弄懂前两个关于二叉树的题这题就很顺了,不过看完题解才知道这道题原来是要将每个结点的左右孩子反转orz,误打误撞也对了)

题目分析

给出一堆结点信息(结点个数,它指向的左孩子和右孩子的序号)

注意点

  1. 数据域就是给出信息的下标0~n-1
    2. 这题的中序遍历和层次遍历都是先右后左,和平时的不太一样 (是因为你题目没看懂啊喂(#`O′))

我的解题过程

思路

  1. 先开一个类型为node*的vector数组存储所有结点信息(data,左右孩子初始化为NULL)
  2. 读入题设信息(需要注意的是,如果中序遍历和层次遍历按照平常的写法不变,本题左边读入的右孩子,右边读入的是左孩子),如果有孩子的使其通过下标指向vector中的node*
  3. 然后就是常规操作的中序遍历和层次遍历

bug

代码

#include<iostream>
#include<vector>
#include<string>
#include<queue>

using namespace std;

int n, incnt = 0, layercnt = 0;

struct node {
	int data;
	node *lchild, *rchild;
};

node* create(int data) {
	node *root = new node;//****一定要new
	root->data = data;
	root->lchild = NULL;
	root->rchild = NULL;
	return root;
}

void inorder(node *root) {//中序遍历
	if (root == NULL) return;
	inorder(root->lchild);
	printf("%d", root->data);
	incnt++;
	if (incnt != n) printf(" ");
	inorder(root->rchild);
}

void layerorder(node *root) {//层次遍历
	if (root == NULL) return;
	queue<node*> q;//***注意队列的类型
	q.push(root);
	while (!q.empty()) {
		node *top = q.front();
		q.pop();
		printf("%d", top->data);
		layercnt++;
		if (layercnt != n) printf(" ");
		if (top->lchild != NULL) q.push(top->lchild);
		if (top->rchild != NULL) q.push(top->rchild);
	}
}

int main()
{
	cin >> n;
	vector<node*> nodes(n);
	vector<int> hashTable(n, 0);
	for (int i = 0; i < n; i++) {
		nodes[i] = create(i);
	}
	for (int i = 0; i < n; i++) {
		string right, left;
		cin >> right >> left;
		if (right != "-") {
			hashTable[stoi(right)] = 1;
			nodes[i]->rchild = nodes[stoi(right)];
		}
		if (left != "-") {
			hashTable[stoi(left)] = 1;
			nodes[i]->lchild = nodes[stoi(left)];
		}
	}
	int head = 0;
	for (head; head < n; head++) {//找到跟结点
		if (hashTable[head] == 0)  break;
	}
	layerorder(nodes[head]);
	printf("\n");
	inorder(nodes[head]);
    return 0;
}

dalao的代码

全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~

借鉴点

本题看自己的即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值