先说一下最基本的概念:
前序遍历:根->左孩子->右孩子。
中序遍历:左孩子->根->右孩子。
后序遍历:左孩子->右孩子->根。
然后是二叉树的存储方式。这里用的是用数组存储二叉树。
先开一个tree[]数组,tree[1]为二叉树的根节点,非零表示存在该节点,反之不存在。对于tree[i],它的左孩子为tree[2*i],右孩子为tree[2*i+1]。
下面祭上三种遍历的代码:
void first(int i)
{
cout << tree[i] << " ";
if(tree[i * 2] != 0)
first(i * 2);
if(tree[i * 2 + 1] != 0)
first(i * 2 + 1);
}
void mid(int i)
{
if(tree[i * 2] != 0)
mid(i * 2);
cout << tree[i] << " ";
if(tree[i * 2 + 1] != 0)
mid(i * 2 + 1);
}
void last(int i)
{
if(tree[i * 2] != 0)
last(i * 2);
if(tree[i * 2 + 1] != 0)
last(i * 2 + 1);
cout << tree[i] << " ";
}
可以看出,非常简单。。。
code[vs]-3143:http://www.codevs.cn/problem/3143/
祭上题解:
i表示整体二叉树的框架,tree[i]数组存第i个节点是第tree[i]个点,用mp[xc]存第xc个节点是第mp[xc]个点。
#include <iostream>
#include <map>
using namespace std;
int tree[101];
map<int, int> mp;
void first(int i)
{
cout << tree[i] << " ";
if(tree[i * 2] != 0)
first(i * 2);
if(tree[i * 2 + 1] != 0)
first(i * 2 + 1);
}
void mid(int i)
{
if(tree[i * 2] != 0)
mid(i * 2);
cout << tree[i] << " ";
if(tree[i * 2 + 1] != 0)
mid(i * 2 + 1);
}
void last(int i)
{
if(tree[i * 2] != 0)
last(i * 2);
if(tree[i * 2 + 1] != 0)
last(i * 2 + 1);
cout << tree[i] << " ";
}
int main()
{
tree[1] = 1;
mp[1] = 1;
int n, lc, rc;
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> lc >> rc;
int va = mp[i];
tree[2 * va] = lc;
mp[lc] = 2 * va;
tree[2 * va + 1] = rc;
mp[rc] = 2 * va + 1;
}
first(1);
cout << endl;
mid(1);
cout << endl;
last(1);
cout << endl;
}