微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【数据结构】·【二叉树】

搞懂递归过程,结构基本和单链表结构类似,多了个link域。其他的(计算高,返回结点)都差不多也就不敲了,实现前序建立二叉树,中序遍历。

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T>
struct BinTreeNode{
	T data;
	BinTreeNode<T> *leftChild,*rightChild;
	BinTreeNode(T& item){
		data=item;
		leftChild=NULL;
		rightChild=NULL;
	}
	BinTreeNode(){}
};

template<class T>
class BinaryTree{
public:
	BinTreeNode<T> *root;
	T RefValue;

	BinaryTree(){}
	BinaryTree(T value){
		RefValue=value;
	}
	~BinaryTree(){
		destroy(root);
	}
	
	void CreatBinTree(istream& in,BinTreeNode<T> *& subTree);
	void destroy(BinTreeNode<T> *& subTree);
	void inorder(ostream& out,BinTreeNode<T> *& subTree);//中序遍历
	void visit(BinTreeNode<T>* p){
		cout<<p->data<<endl;
	}
	friend istream& operator >>(istream& is,BinaryTree<T>& Tree){
		Tree.CreatBinTree(is,Tree.root);
		return is;
	}
	friend ostream& operator <<(ostream& os,BinaryTree<T>& Tree){    //重载<<输出二叉树
		os<<"二叉树的中序遍历\n";
		Tree.inorder(os,Tree.root);
		os<<endl;
		return os;
	}	
};


template<class T>
void BinaryTree<T>::CreatBinTree(istream& in,BinTreeNode<T> *& subTree){   
	T item;
	if(!in.eof()){
		in>>item;
		if(item!=RefValue){
			subTree =new BinTreeNode<T>(item);
			if(subTree == NULL){
				cerr<<"存储分配错误!"<<endl;
				exit(1);
			}
			CreatBinTree(in,subTree->leftChild);
			CreatBinTree(in,subTree->rightChild);
		}
		else
			subTree=NULL;
	}
}


template<class T>
void BinaryTree<T>::destroy(BinTreeNode<T> *& subTree){
	if(subTree!=NULL){
		destroy(subTree->leftChild);
		destroy(subTree->rightChild);
		delete subTree;
	}
}

template<class T>
void BinaryTree<T>::inorder(ostream& out,BinTreeNode<T> *& subTree){
	if(subTree!=NULL){		
		inorder(out,subTree->leftChild);
		out<<subTree->data<<' ';
		inorder(out,subTree->rightChild);
	}	
}

void main(){
	BinaryTree<char> tree;
	tree.RefValue='#';
	
	cin>>tree;
	cout<<tree;
	
}
运行截图:


二叉树原型:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐