树的遍历 (和) 玩转二叉树 的总结博客
树的遍历:
关键在与如何利用中序和后序建树。
中序的作用,提供了左右子树的所有节点的分布!
前序,后序的作用:就是第一个元素(最后一个元素)提供了根节点,让中序找到子树的分布情况。
#include<iostream> #include<queue> #include<vector> using namespace std; const int maxn = 100; int af[maxn], in[maxn], n; struct node{ int l, r; }tree[maxn]; int biuld(int al, int ar, int bl, int br){ if (al > ar)return 0; int root, p1, len; root = af[br]; for (p1 = al; p1 <= ar; ++p1)if (in[p1] == root)break; len = p1 - al; tree[root].l = biuld(al, p1 - 1, bl, bl + len-1); tree[root].r = biuld(p1 + 1, ar, bl + len, br - 1); return root; } void BFS(int x){ queue<int>q; vector<int>v; q.push(x); while (!q.empty()){ int root = q.front(); q.pop(); if (root == 0)break; v.push_back(root); if (tree[root].l)q.push(tree[root].l); if (tree[root].r)q.push(tree[root].r); } int len = v.size(); for (int i = 0; i < len; ++i) cout << v[i] << " \n"[i == len - 1]; } int main(){ cin >> n; for (int i = 0; i < n; ++i)cin >> af[i]; for (int i = 0; i < n; ++i)cin >> in[i]; int root = biuld(0, n - 1, 0, n - 1); BFS(root); }
玩转二叉树:
这里的改变只是在建树的时候,把原本左子树放在实际的右子树上,原本的右子树放在左子树上。
#include<iostream> #include<queue> #include<vector> using namespace std; const int maxn = 1e3; struct node{ int l, r; }tree[maxn]; int pre[maxn], in[maxn], n; int build(int al, int ar, int bl, int br){ if (al > ar)return 0; int root, p1, len; root = pre[bl]; for (p1 = al; p1 <= ar; ++p1)if (in[p1] == root)break; len = p1 - al; tree[root].r = build(al, p1 - 1, bl + 1, bl + len ); tree[root].l = build(p1 + 1, ar, bl + len + 1, br); return root; } void BFS(int x){ queue<int>q; vector<int>v; q.push(x); while (!q.empty()){ int root = q.front(); q.pop(); if (root == 0)break; v.push_back(root); if (tree[root].l)q.push(tree[root].l); if (tree[root].r)q.push(tree[root].r); } int size = v.size(); for (int i = 0; i < size; ++i) cout << v[i] << " \n"[i == size - 1]; } int main(){ cin >> n; for (int i = 0; i < n; ++i)cin >> in[i]; for (int i = 0; i < n; ++i)cin >> pre[i]; int root = build(0, n - 1, 0, n - 1); BFS(root); }