C++实现二叉树的遍历,含测试代码
#ifndef BINARYTREE_H
#define BINARYTREE_H
#include <iostream>
#include <stack>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
template <typename T>
struct BinTreeNode
{
T data;
BinTreeNode<T> *leftChild, *rightChild;
BinTreeNode() : leftChild(NULL), rightChild(NULL) {
}
BinTreeNode(T x, BinTreeNode<T> *l = NULL, BinTreeNode<T> *r = NULL) : data(x), leftChild(l), rightChild(r) {
}
};
template <typename T>
class BinaryTree
{
public:
BinaryTree() : root(NULL) {
}
BinaryTree(T value) : RefValue(value), root(NULL) {
}
~BinaryTree() {
Destroy(root); }
void CreateBinTree() {
CreateBinTree(root); }
void CreateBinTree_PreOrder() {
CreateBinTree_PreOrder(root); }
void CreateBinTreeBy_Pre_In(const char *pre, const char *in)
{
int n = strlen(pre);
CreateBinTreeBy_Pre_In(root, pre, in, n);
}
void CreateBinTreeBy_Post_In(const char *post, const char *in)
{
int n = strlen(post);
CreateBinTreeBy_Post_In(root, post, in, n);
}
void PreOrder() {
PreOrder(root); }
void InOrder() {
InOrder(root); }
void PostOrder() {
PostOrder(root); }
void PreOrder_NoRecurve() {
PreOrder_NoRecurve(root); }
void InOrder_NoRecurve() {
InOrder_NoRecurve(root); }
void PostOrder_NoRecurve() {
PostOrder_NoRecurve(root); }
void LevelOrder() {
LevelOrder(root); }
BinTreeNode<T> *getRoot() const
{
return root;
}
BinTreeNode<T> *Parent(BinTreeNode<T> *current)
{
return (root == NULL || root == current) ? NULL : Parent(root, current);
}
BinTreeNode<T> *LeftChild(BinTreeNode<T> *current)
{
return (current != NULL) ? current->leftChild : NULL;
}
BinTreeNode<T> *RightChild(BinTreeNode<T> *current)
{
return (current != NULL) ? current->rightChild : NULL;
}