【数据结构】迭代器实现二叉树的中序遍历

迭代器

template<class T,class Ref,class Ptr>
struct __TreeIterator
{
	typedef BinTreeNode<T> Node;
	typedef __TreeIterator<T,Ref,Ptr> Self;
	__TreeIterator()
	{}
	__TreeIterator(Node* node)
		:_node(node)
	{}
	Ref operator*()
	{
		assert(_node);
		return _node->_date;
	}
	Self& operator++()
	{
		assert(_node);
		if(_node->RightTag==Link)
		{
			Node* right=_node->rightchild;
			while (right&&right->LeftTag==Link)
			{
				right=right->leftchild;
			}
			_node=right;
		}
		else
		{
			_node=_node->rightchild;
		}
		return *this;
	}
	Self& operator++(int)
	{
		Self tmp(*this);
		++(*this);
		return tmp;
	}
	Self& operator--()
	{
		assert(_node);
		if(_node->LeftTag=Link)
		{
			Node* left=_node->leftchild;
			while (left&&left->RightTag==Link)
			{
				left=left->rightchild;
			}
			_node=left;
		}
		else
		{
			_node=_node->leftchild;
		}
		return *this;
	}
	bool operator!=(const Self s) const
	{
		return _node!=s._node;
	}
	Node* _node;
T表示类型,Ref表示引用,Ptr表示指针

二叉树的实现

需要实现begin和end

template <class T>
class BinTree
{
	typedef BinTreeNode<T> Node;
public:
	typedef __TreeIterator<T,T&,T*> Iterator;
	typedef __TreeIterator<T,const T&,const T* > ConstIterator;
	Iterator Begin()
	{
		Node* cur=_root;
		while (cur&&cur->LeftTag==Link)
		{
			cur=cur->leftchild;
		}
		return Iterator(cur);
	}
	ConstIterator Begin()const;
	Iterator End()
	{
		return Iterator(0);
	}
	ConstIterator End()const;
	BinTree()
		:_root(NULL)
	{}
	BinTree(T* a,size_t size,const T& invalid)
		:_root(NULL)
	{
		size_t index=0;
		_CreateTree( _root,a,size,index,invalid);
	}
	void InOrderThead()
	{
		Node* pre=NULL;
		_InOrderThead(_root,pre);
	}
protected:
	void  _CreateTree(Node*& root,T a[],size_t size,size_t& index ,const T& invalid)
	{
		assert(a);
		if(index< size&& a[index]!=invalid)
		{
			root=new Node(a[index]);
			_CreateTree(root->leftchild,a,size,++index,invalid);
			_CreateTree(root->rightchild,a,size,++index,invalid);

		}
	}
	void _InOrderThead(Node* root,Node* &pre)
	{
     if(root==NULL)
	 return ;
	 _InOrderThead(root->leftchild,pre);
	 if(root->leftchild==NULL)
	 {
		 root->LeftTag=Thread;
		 root->leftchild=pre;
	 }
	 if(pre&&pre->rightchild==NULL)
	 {
		 pre->RightTag=Thread;
		 pre->rightchild=root;
	 }
	 pre=root;
	 _InOrderThead(root->rightchild,pre);
	}
private:
	Node* _root;
}; 

测试用例

void test()
{
	int a1[10]={1,2,3,'#','#',4,'#','#',5,6};
	BinTree<int> t1(a1,10,'#');
	t1.InOrderThead();
	//t1.InOrder_NonR();
	BinTree<int>::Iterator it=t1.Begin();
	cout<<endl;
	while (it!=t1.End())
	{
		cout<<*it<<" ";
		++it;
	}
	cout<<endl;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值