树的遍历
来源:互联网 发布:微信助力软件 编辑:程序博客网 时间:2024/06/05 22:52
/*由后序遍历与中序遍历求层次遍历*/#include <iostream>#include <vector>#include <cstdlib>#include <list>using namespace std;int n;vector<int> postOrder;vector<int> inOrder;int cur;typedef struct TNode *Tree;struct TNode{ Tree lchild; Tree rchild; int num;};int findRootIndex(int root){ for (int i = 0; i < n; i++) { if (inOrder[i] == root) return i; } return -1;}Tree createTree(int left, int right){ if (left > right) return NULL; int root = postOrder[cur--]; int rootIndex = findRootIndex(root); Tree T = new TNode; T->num = root; if (left == right) { T->lchild = NULL; T->rchild = NULL; } else { T->rchild = createTree(rootIndex + 1, right); T->lchild = createTree(left, rootIndex - 1); } return T;}void BFS(Tree T){ list<Tree> queue; queue.push_back(T); vector<int> p; while (!queue.empty()) { Tree T = queue.front(); queue.pop_front(); p.push_back(T->num); if(T->lchild!=NULL) queue.push_back(T->lchild); if(T->rchild!=NULL) queue.push_back(T->rchild); } for (int i = 0; i < p.size() - 1; i++) { cout << p[i] << ' '; } cout << p[p.size() - 1] << endl;}int main(){ cin >> n; cur = n - 1; int temp; for (int i = 0; i < n; i++) { cin >> temp; postOrder.push_back(temp); } for (int i = 0; i < n; i++) { cin >> temp; inOrder.push_back(temp); } Tree T = createTree(0, cur); BFS(T); system("pause"); return 0;}
0 0
- 二叉树的遍历(层遍历和深度遍历)
- 二叉树的前序中序后序遍历,非递归遍历 层次遍历
- 二叉树的先中后序遍历,递归遍历,非递归遍历
- 二叉树遍历-----前序后序迭代遍历的新思路
- 二叉树的遍历-按层次遍历
- 二叉树的遍历(递归遍历)
- 二叉树的遍历-层次遍历
- 树的遍历
- 六、 树的遍历
- 二叉树的遍历
- haffman树的遍历
- 二叉树的遍历
- 树的各种遍历
- 树的遍历
- 二叉树的遍历
- C++树的遍历
- Java树的遍历
- 树的简单遍历
- dyld: Library not loaded: @rpath/MySDK.framework/MySDK 错误解决
- 关于tcp_wrappers防火墙
- 不良资产处置(十):关于不良资产处置市场化的思考
- Java执行Linux命令并返回命令结果
- java正则表达式
- 树的遍历
- Android 开机时间慢问题debug
- 无线轮播
- HDU 4034 Graph
- go 语言精华学习贴
- 不可重现的bug如何处理
- 游戏开发入门02
- 常用类和方法
- 如何处理高并发情况下的DB插入