原理剖析
代码
#include<bits/stdc++.h>
#pragma warning(disable:4996)
#pragma warning(disable:4703)
#pragma warning(disable:4700)
using namespace std;
typedef struct Tree {
string key;
int lchild;
int rchild;
}BiTree;
string PrintTree(BiTree* T, vector<BiTree*> a) {
if (T->lchild != -1 && T->rchild != -1) {
return "("+ PrintTree(a[T->lchild],a)+ T->key + PrintTree(a[T->rchild], a) + ")";
}
if (T->lchild == -1 && T->rchild != -1) {
return "(" + T->key + PrintTree(a[T->rchild], a) + ")";
}
if (T->lchild != -1 && T->rchild == -1) {
return "(" + T->key + PrintTree(a[T->lchild], a) + ")";
}
if (T->lchild == -1 && T->rchild == -1) {
return T->key ;
}
}
int main() {
int number;
cin >> number;
vector<BiTree*> a(1);//先垫掉0空间
int b[25];//map数组
for (int i = 0; i != number; i++) {
BiTree* node = new BiTree;
cin >> node->key >> node->lchild >> node->rchild;
a.push_back(node);
if (node->lchild != -1) {
b[node->lchild] = 1;
}
if (node->rchild != -1) {
b[node->rchild] = 1;
}
}
BiTree* root;//必须在for外部定义
for (int i = 1; i <= number; i++) {//vector是从0开始的
if (b[i] != 1) {
root = a[i];//由于i的作用域仅在for内,因此要在循环内定义
break;
}
}
string ans = PrintTree(root, a);//根节点是肯定要的,其次存放结点的vector肯定也要
if(ans[0]=='(')//测试点2就需要这句,原因是在边界只有1个字符时,是没有()
ans=ans.substr(1, ans.size() - 2);
cout << ans;
return 0;
}
输出的一种等价写法
if (a.size() == 2) {//测试点2就需要这句,原因是在边界只有1个字符时,是没有()
cout << root->key;
}
else{
cout << ans.substr(1, ans.size() - 2);//默认从0开始,size包含了结尾的\0,因此截断掉首位为1——size-2
}
本文详细解析了二叉树的结构与遍历算法,通过C++代码实现了二叉树的前序、中序、后序遍历,并将遍历结果转换为字符串形式进行输出。文章深入探讨了如何寻找根节点,以及在不同边界条件下的处理方法。
6万+

被折叠的 条评论
为什么被折叠?



