层次遍历以二叉链表存储的树或森林,#表示空格。输出序列为:ABCDEFGH。
层次遍历以二叉链表存储的树或森林,#表示空格。输出序列为:ABCDEFGH。
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- CSDN专家-Time 2021-12-31 15:18关注
参考二叉树的建成与遍历。
#include<iostream> #include <vector> #include <stack> #include <queue> #pragma warning(disable:4996) using namespace std; int n = 8; vector<char> tree = { 'A', 'B', 'C', 'D', 'E', '*', 'F' }; vector<int> visited = { 0,0,0,0,0,0,0,0 }; int hasChild(int index) { if (index * 2 + 1 >= 7) { return -1; } // 左孩子 if (!visited[index * 2 + 1] && tree[index * 2 + 1] != '*') { return index * 2 + 1; } // 右孩子 else if (!visited[index * 2 + 2] && tree[index * 2 + 2] != '*') { return index * 2 + 2; } else { return -1; } } int main() { stack<int> dfs; int node = 0; dfs.push(node); while (dfs.size() != 0) { // 查询子节点 // 子节点在上文中说过,是 node*2+1 node*2+2 node = dfs.top(); int child = hasChild(node); if ( child != -1) { dfs.push(child); visited[child] = 1; node = dfs.top(); } else { node = dfs.top(); dfs.pop(); } //,不在算法内,只是为了打印栈内元素 cout << "栈内元素:从栈顶到栈底=>"; stack<int> s2; s2 = dfs; while (!s2.empty()) { cout << tree[s2.top()] << " "; s2.pop(); } cout << endl; } cout << endl; visited = { 0,0,0,0,0,0,0,0 }; queue<int> bfs; node = 0; bfs.push(node); while (bfs.size() != 0) { node = bfs.front(); int child = hasChild(node); // 第一次访问左孩子 if (child != -1) { bfs.push(child); visited[child] = 1; node = bfs.front(); } child = hasChild(node); if (child != -1) { bfs.push(child); visited[child] = 1; node = bfs.front(); } else { node = bfs.front(); bfs.pop(); } //,不在算法内,只是为了打印栈内元素 cout << "队内元素:从队首到队尾=>"; queue<int> s2; s2 = bfs; while (!s2.empty()) { cout << tree[s2.front()] << " "; s2.pop(); } cout << endl; } cout << endl; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 WPF 大屏看板表格背景图片设置
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示