1. 程式人生 > >【C++】中序線索化二叉樹及其遍歷

【C++】中序線索化二叉樹及其遍歷

<pre name="code" class="cpp"><pre name="code" class="cpp">#include<iostream>
using namespace std;
enum PointTag
{
	LINK,
	THREAD,
};
struct BinTreeThingNode
{
	char _data;
	BinTreeThingNode*_left;
	BinTreeThingNode*_right;
	PointTag _leftTag;
	PointTag _rightTag;
	BinTreeThingNode(const char &data)
		:_data(data)
		, _left(NULL)
		, _right(NULL)
		, _leftTag(LINK)
		, _rightTag(LINK)
	{}
};
class BinTreeThreading
{
public:
	BinTreeThreading(const char *str)
	{
		_CreatBinTreeThreading(_root,str);//遞迴建立二叉樹
	}
	void InOderThread()//中序線索化
	{
		BinTreeThingNode*prev = NULL;//prev是訪問的上一節點
		_InOderThread(_root, prev);//中序線索化的實現
	}
	void InOderSort()//通過中序線索化中序遍歷二叉樹
	{
		BinTreeThingNode*cur = _root;
		while (cur)
		{
			while (cur&&cur->_leftTag != THREAD)
			{
				cur = cur->_left;
			}
			cout << cur->_data << " ";
			while (cur&&cur->_rightTag == THREAD)
			{
				cur = cur->_right;
				cout << cur->_data << " ";
			}
			if (cur)
			{
				cur = cur->_right;
			}
		}
	}
	
protected:
	void _CreatBinTreeThreading(BinTreeThingNode*&root, const char *&str)
	{
		if (*str!='#'&&*str!='\0')
		{
			root = new BinTreeThingNode(*str);
			_CreatBinTreeThreading(root->_left,++str);
			if (*str != '\0')
			{
				_CreatBinTreeThreading(root->_right,++str);
			}
		}
	}
	void _InOderThread(BinTreeThingNode*&cur, BinTreeThingNode*&prev)
	{
		if (cur)
		{
			_InOderThread(cur->_left, prev);
			//當前節點cur的前驅
			if (cur->_left == NULL)
			{
				cur->_leftTag = THREAD;
				cur->_left = prev;//當前節點的前驅是上一節點
			}
			//上一節點prev的後繼
			if (prev&&prev->_right == NULL)
			{
				prev->_rightTag = THREAD;
				prev->_right = cur;//上一節點的後繼是當前節點
			}
			prev = cur;//更新上一訪問的節點
			_InOderThread(cur->_right, prev);
		}
	}

	
private:
	BinTreeThingNode*_root;
};

void Test()
{
	BinTreeThreading bt("123##4##56");
	bt.InOderThread();
	bt.InOderSort();
}
int main()
{
	Test();
	system("pause");
	return 0;
}