BiTreeNode.h
#pragma once
template<class T> class BiTreeNode
{
private:
BiTreeNode<T> * leftChild;
BiTreeNode<T> * rightChild;
public:
T data;
BiTreeNode() :leftChild(NULL), rightChild(NULL) {}
BiTreeNode(T item, BiTreeNode<T>* left = NULL, BiTreeNode<T>* right = NULL) :
data(item), leftChild(left), rightChild(right) {}
~BiTreeNode() {}
BiTreeNode<T> *& Left(void) { return leftChild; }
BiTreeNode<T> *& Right(void) { return rightChild; }
};
template<class T> BiTreeNode<T> * GetTreeNode(const T item, BiTreeNode<T> * left = NULL,
BiTreeNode<T>* right = NULL)
{
BiTreeNode<T>*p;
p = new BiTreeNode<T>(item, left, right);
return p;
}
//前序遍历
template<class T> void preOrder(BiTreeNode<T>*t, void Visit(T item))
{
if (t != NULL)
{
Visit(t->data);
preOrder(t->Left(), Visit);
preOrder(t->Right(), Visit);
}
}
//中序遍历
template<class T> void inOrder(BiTreeNode<T>*t, void Visit(T item))
{
if (t != NULL)
{
preOrder(t->leftChild, Visit);
Visit(t->data);
preOrder(t->rightChild, Visit);
}
}
//后序遍历
template<class T> void postOrder(BiTreeNode<T>*t, void Visit(T item))
{
if (t != NULL)
{
preOrder(t->Left(), Visit);
preOrder(t->Right(), Visit);
Visit(t->data);
}
}
template <class T> void Destroy(BiTreeNode<T> *&root)
{
if (root != NULL && root->Left() != NULL)
{
Destroy(root->Left());
}
if (root != NULL && root->Right() != NULL)
{
Destroy(root->Right());
}
cout << root->data << " ";
delete root;
}
template<class T> void printBiTree(BiTreeNode<T> *&root, int level)
{
if (root != NULL)
{
printBiTree(root->Right(), level + 1);
if (level != 0)
{
for (int i = 0; i < 6 * (level - 1); i++)
{
cout << " ";
}
cout << root->data << endl;
}
printBiTree(root->Left(), level + 1);
}
}
template<class T> BiTreeNode<T>* Search(BiTreeNode<T> *t, T x)
{
BiTreeNode<T> *p;
//空二叉树时,查找失败,出口
if (t == NULL)
return NULL;
if (t->data == x)
return t;
if (t->Left() != NULL)
{
//在左子树查找
p = Search(t->Left(), x);
//查找成功是结束递归过程
if (p != NULL)
return p;
}
if (t->Right() != NULL)
{
//在左子树查找
p = Search(t->Right(), x);
//查找成功是结束递归过程
if (p != NULL)
return p;
}
return NULL;
}
main.cpp
#include <iostream>
#include "BitreeNode.h"
using namespace std;
void printChar(char item)
{
cout << item << " ";
}
void MakeCharTree(BiTreeNode<char> *&root)
{
BiTreeNode<char> *b, *c, *d, *e, *f, *g, *null = NULL;
g = GetTreeNode('G');
d = GetTreeNode('D', null, g);
b = GetTreeNode('B', d);
e = GetTreeNode('E');
f = GetTreeNode('F');
c = GetTreeNode('C', e, f);
root = GetTreeNode('A', b, c);
}
int main()
{
BiTreeNode<char> *root, *p;
MakeCharTree(root);
cout << "二叉树为:" << endl;
printBiTree(root, 1);
cout << "\n前序遍历节点次数为:";
preOrder(root, printChar);
cout << "\n中序遍历节点次数为:";
preOrder(root, printChar);
cout << "\n后序遍历节点次数为:";
postOrder(root, printChar);
p = Search(root, 'C');
if (p != NULL)
{
cout << "\n查找到的节点数值为:" << p->data;
}
else
{
cout << "\n查找失败";
}
cout << "\n撤销节点次序为:";
Destroy(root);
return 0;
}