二叉树的前中后序遍历
// 二叉树的遍历.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class BinaryTree {
vector<T> tree;
public:
BinaryTree(initializer_list<T> a) :tree(a){}
void preorder(size_t index = 0);
void inorder(size_t index = 0);
void postorder(size_t index = 0);
};
int main()
{
BinaryTree<char> bt{ 'A','B','C','D',0,'E','F','G','H',0,0,0,'I' };
bt.preorder(); cout << endl;
bt.inorder(); cout << endl;
bt.postorder(); cout << endl;
}
template<typename T>
void BinaryTree<T>::preorder(size_t index)
{
if (index >= tree.size() || tree[index] == 0)return;
int left = index * 2 + 1, right = index * 2 + 2;
cout << tree[index] << ' ';
preorder(left);
preorder(right);
}
template<typename T>
void BinaryTree<T>::inorder(size_t index)
{
if (index >= tree.size() || tree[index] == 0)return;
int left = index * 2 + 1, right = index * 2 + 2;
inorder(left);
cout << tree[index] << ' ';
inorder(right);
}
template<typename T>
void BinaryTree<T>::postorder(size_t index)
{
if (index >= tree.size() || tree[index] == 0)return;
int left = index * 2 + 1, right = index * 2 + 2;
postorder(left);
postorder(right);
cout << tree[index] << ' ';
}