c++之二叉树的递归实现与递归遍历

CreateBinaryTree.h

template class BinaryTree;

template 
class BinTreeNode
{
	friend class BinaryTree;
	T data;
	BinTreeNode *lchild;
	BinTreeNode *rchild;
};

template
class BinaryTree
{
public:
	BinaryTree(){ root = 0; };//

	void CreateTree();//创建(按照前序规则)
	void CreateTree(BinTreeNode *¤tnode);

	void PreOrder();//前序
	void PreOrder(BinTreeNode *¤tnode);

	void InOrder();//中序
	void InOrder(BinTreeNode *¤tnode);

	void PostOrder();//后序
	void PostOrder(BinTreeNode *¤tnode);

private:
	BinTreeNode *root;
};

template
void BinaryTree::CreateTree()
{
	CreateTree(root);
}
template
void BinaryTree::CreateTree(BinTreeNode *¤tnode)
{
	char ch;
	if ((ch = getchar()) == '#')
	{
		currentnode = 0;
	}
	else
	{
		currentnode = new BinTreeNode();
		currentnode->data = ch;
		CreateTree(currentnode->lchild);
		CreateTree(currentnode->rchild);
	}
}

template
void BinaryTree::PreOrder()
{
	cout << "前序遍历(根-左-右)为";
	PreOrder(root);
}
template
void BinaryTree::PreOrder(BinTreeNode *¤tnode)
{
	if (currentnode)
	{
		cout << currentnode->data << ' ';
		PreOrder(currentnode->lchild);
		PreOrder(currentnode->rchild);
	}
}

template
void BinaryTree::InOrder()
{
	cout << "中序遍历(左-根-右)为";
		InOrder(root);
}
template
void BinaryTree::InOrder(BinTreeNode *¤tnode)
{
	if (currentnode)
	{
		InOrder(currentnode->lchild);
		cout << currentnode->data << ' ';
		InOrder(currentnode->rchild);
	}
}

template
void BinaryTree::PostOrder()
{
	cout << "后序遍历(左-右-根)为";
		PostOrder(root);
}
template
void BinaryTree::PostOrder(BinTreeNode *¤tnode)
{
	if (currentnode)
	{
		PostOrder(currentnode->lchild);
		PostOrder(currentnode->rchild);
		cout << currentnode->data << ' ';
	}
}

main.cpp

#include "CreateBinaryTree.h"
#include 
using namespace std;

int main()
{
	BinaryTree Tree1;
	Tree1.CreateTree();
	Tree1.PreOrder();
	cout << endl;
	Tree1.InOrder();
	cout << endl;
	Tree1.PostOrder();
	cout << endl;
	system("pause");
	return 0;
}

结果为:
c++之二叉树的递归实现与递归遍历_第1张图片

你可能感兴趣的:(c++之二叉树的递归实现与递归遍历)