洛谷 新二叉树
洛谷p1305题
题目描述
输入一串二叉树,输出其前序遍历。
输入格式
第一行为二叉树的节点数 n n n。( 1 ≤ n ≤ 261 ≤ n ≤ 26 1 \leq n \leq 261≤n≤26 1≤n≤261≤n≤26)
后面 n n n 行,每一个字母为节点,后两个字母分别为其左右儿子。
空节点用 *
表示
输出格式
二叉树的前序遍历。
输入输出样例
输入
6
abc
bdi
cj*
d**
i**
j**
输出
abdicj
代码如下
#include<iostream>
#include<string.h>
#include<queue>
#include<list>
#include<map>
using namespace std;
struct TreeNode {
int left = -1;
int right = -1;
int parent = -1;
};
TreeNode Tree[30];
//根左右 前序遍历
void prePrint(int root) {
cout << char(root - 1 + 'a');//输出根
if (Tree[root].left != -1)//左子树不为空时候进行(递归)找左子树中的根左右
prePrint(Tree[root].left);//递归
if (Tree[root].right != -1)//右子树不为空时候进行(递归)找右子树中的根左右
prePrint(Tree[root].right);//递归
}
void inOrderPrint(int root) {
if (Tree[root].left != -1)//左子树不为空时候进行(递归)找左子树中的根左右
prePrint(Tree[root].left);//递归
cout << char(root - 1 + 'a');//输出根
if (Tree[root].right != -1)//右子树不为空时候进行(递归)找右子树中的根左右
prePrint(Tree[root].right);//递归
}
void postOrderPrint(int root) {
if (Tree[root].left != -1)//左子树不为空时候进行(递归)找左子树中的根左右
prePrint(Tree[root].left);//递归
if (Tree[root].right != -1)//右子树不为空时候进行(递归)找右子树中的根左右
prePrint(Tree[root].right);//递归
cout << char(root - 1 + 'a');//输出根
}
void levelPrint(int root) {
queue<int> q;//首先定义队列,用于存储层次信息
q.push(root);//祖先节点入队
while (!q.empty()) {//如果队列非空,则取队头,找可达并未访问过的点入队(即下一层的节点入队)
int temp = q.front();//访问队头
q.pop();//拿走队头
cout << char(temp - 1 + 'a');//输出层次信息(队头)
if (Tree[temp].left != -1)//左节点(达并未访问过的点)非空则入队
q.push(Tree[temp].left);
if (Tree[temp].right != -1)//右节点(达并未访问过的点)非空则入队
q.push(Tree[temp].right);
}
}
int main() {
int n;
cin >> n;//输入n个节点
while (n--) {
string s;//输入节点信息
cin >> s;//输入节点信息
if (s[1] != '*') {//s[1]左节点 左节点非空才可以赋值
Tree[s[0] - 'a' + 1].left = s[1] - 'a' + 1;// s[0]-'a'+1 根对应的数字 s[1]-'a'+1左孩子对应的数字
Tree[s[1] - 'a' + 1].parent = s[0] - 'a' + 1;
}
if (s[2] != '*') {//s[2]右节点 右节点非空才可以赋值
Tree[s[0] - 'a' + 1].right = s[2] - 'a' + 1;// s[0]-'a'+1 根对应的数字 s[2]-'a'+1右孩子对应的数字
Tree[s[2] - 'a' + 1].parent = s[0] - 'a' + 1;
}
}
int root;//祖先节点
// 1\没有父亲,parent==-1
// 2\left!=-1||right!=-1
for (int i = 1; i <= 26; i++) {
if (Tree[i].parent == -1 && (Tree[i].left != -1 || Tree[i].right != -1)) {
root = i;
break;
}
}
prePrint(root);//先序遍历
cout << endl;
inOrderPrint(root);//中序遍历
cout << endl;
postOrderPrint(root);//后序遍历
cout << endl;
levelPrint(root);//层序遍历
return 0;
}