解题过程的小记录,如有错误欢迎指出。
难度:三星(弄懂前两个关于二叉树的题这题就很顺了,不过看完题解才知道这道题原来是要将每个结点的左右孩子反转orz,误打误撞也对了)
题目分析
给出一堆结点信息(结点个数,它指向的左孩子和右孩子的序号)
注意点
- 数据域就是给出信息的下标0~n-1
2. 这题的中序遍历和层次遍历都是先右后左,和平时的不太一样(是因为你题目没看懂啊喂(#`O′))
我的解题过程
思路
- 先开一个类型为node*的vector数组存储所有结点信息(data,左右孩子初始化为NULL)
- 读入题设信息(需要注意的是,如果中序遍历和层次遍历按照平常的写法不变,本题左边读入的右孩子,右边读入的是左孩子),如果有孩子的使其通过下标指向vector中的node*
- 然后就是常规操作的中序遍历和层次遍历
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的代码
全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~
借鉴点
本题看自己的即可