【发布时间】:2021-07-14 08:14:57
【问题描述】:
我需要构造一棵给定深度和后序遍历的树,然后我需要生成对应的前序遍历。示例:
Depth: 2 1 3 3 3 2 2 1 1 0
Postorder: 5 2 8 9 10 6 7 3 4 1
Preorder(output): 1 2 5 3 6 8 9 10 7 4
我定义了两个包含后序序列和深度的数组。在那之后,我想不出一个算法来解决它。
这是我的代码:
int postorder[1000];
int depth[1000];
string postorder_nums;
getline(cin, postorder_nums);
istringstream token1(postorder_nums);
string tokenString1;
int idx1 = 0;
while (token1 >> tokenString1) {
postorder[idx1] = stoi(tokenString1);
idx1++;
}
string depth_nums;
getline(cin, depth_nums);
istringstream token2(depth_nums);
string tokenString2;
int idx2 = 0;
while (token2 >> tokenString2) {
depth[idx2] = stoi(tokenString2);
idx2++;
}
Tree tree(1);
【问题讨论】:
-
您的树代码不存在...将数字读取为字符串然后将这些字符串转换为数字是没有意义的。至于主要任务:尝试在一张纸上画树。然后,尝试想出一个可以容纳树的数据结构。深思:它是二叉树还是更复杂的东西?你会使用指针还是构建扁平树?
-
它不是二叉树,它只是一棵可以有三个或更多孩子的普通树。我会再次检查我的问题并感谢您的评论。
标签: c++ algorithm tree preorder postorder