【数据结构】 二叉树的实现

前端之家收集整理的这篇文章主要介绍了【数据结构】 二叉树的实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习数据结构基础,如有错误,请指正。



/************************************************************************
   数据结构:二叉树的实现,创建、先序、中序、后序遍历(递归实现)                                                               
************************************************************************/

#ifndef __BITTREE_H__
#define __BITTREE_H__

typedef char ElemType;

struct BitNode{
	ElemType data;
	BitNode *lChild;
	BitNode *rChild;
};

class BitTree{
public:
	BitTree();
	~BitTree();
	
	void creatBitTree(BitNode* &tree);
	void preOrderTraverseTree(BitNode* tree);
	void inOrderTraverseTree(BitNode* tree);
	void posOrderTraverseTree(BitNode* tree);
	void visit(ElemType e);

	BitNode *bitTree;
};


#endif // __BITTREE_H__



#include "BitTree.h"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

BitTree::BitTree()
{
	this->bitTree = NULL;
}
BitTree::~BitTree()
{

}

void BitTree::creatBitTree(BitNode* &tree)
{
	// 先序、递归建树
	cout<<"enter a node char:";
	char ch = NULL;
	cin>>ch;
	if ( 'q' == ch )
	{
		tree = NULL;
	}
	else{
		tree = new BitNode();
		tree->data = ch;

		this->creatBitTree( tree->lChild );
		this->creatBitTree( tree->rChild );
	}
}
void BitTree::preOrderTraverseTree(BitNode* tree)
{
	if (tree)
	{
		visit(tree->data);
		preOrderTraverseTree(tree->lChild);
		preOrderTraverseTree(tree->rChild);
	}
	
}
void BitTree::inOrderTraverseTree(BitNode* tree)
{
	if (tree)
	{		
		preOrderTraverseTree(tree->lChild);
		visit(tree->data);
		preOrderTraverseTree(tree->rChild);
	}
}
void BitTree::posOrderTraverseTree(BitNode* tree)
{
	if (tree)
	{
		preOrderTraverseTree(tree->lChild);
		preOrderTraverseTree(tree->rChild);
		visit(tree->data);
	}
}
void BitTree::visit(ElemType e)
{
	cout<<e;
}

int main()
{
	BitTree *aTree = new BitTree();
	aTree->creatBitTree(aTree->bitTree);

	cout<<"preOrder traverse Tree:"<<endl;
	aTree->preOrderTraverseTree(aTree->bitTree);
	cout<<endl;

	cout<<"inOrder traverse Tree:"<<endl;
	aTree->inOrderTraverseTree(aTree->bitTree);
	cout<<endl;

	cout<<"posOrder traverse Tree:"<<endl;
	aTree->posOrderTraverseTree(aTree->bitTree);
	cout<<endl;

	getchar();
	return 0;
}
原文链接:https://www.f2er.com/datastructure/383260.html

猜你在找的数据结构相关文章