二叉樹遞歸遍歷的時候,將其分爲根、左子樹、右子樹三個部分。
其非遞歸遍歷,也是分爲三個部分,通過數據結構“棧”的入棧出棧操作以及其先入後出的特性,實現其遍歷。
template<class T>
struct BinaryTreeNode
{
T _data;
BinaryTreeNode<T>* _left;
BinaryTreeNode<T>* _right;
BinaryTreeNode(const T& x)
: _data(x)
, _left(NULL)
, _right(NULL)
{}
};
template<class T>
class BinaryTree
{
typedef BinaryTreeNode<T> Node;
public:
BinaryTree()
:_root(NULL)
{}
BinaryTree(T* a, size_t n, const T& invalid)
{
size_t index = 0;
_root = _CreatTree(a, n, invalid, index);
}
~BinaryTree()
{
_Destroy(_root);
}
void Destroy()//後序遍歷釋放
{
_Destroy(_root);
}
//非遞歸
//前序
void PreOrderNonR()
{
Node* cur = _root;
stack<Node*> s;
while (!s.empty() || cur)
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
cout << top->_data << " ";
s.pop;
cur = top->_right;
}
cout << endl;
}
//中序
void InOrderNonR()
{
Node* cur = _root;
stack<Node*> s;
while (!s.empty() || cur)
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
cout << top->_data << " ";
s.pop;
cur = top->_right;
}
cout << endl;
}
//後序非遞歸
void PostOrderNonR()
{
stack<Node*> s;
Node* prev = NULL;
Node* cur = _root;
while (!s.empty() || cur)
{
while (cur)
{
s.push(cur);
cur = cur->_left;
}
Node* top = s.top();
if (top->_right = NULL || top->_right == prev)
{
cout << top->_data << " ";
prev = top;
s.pop();
}
else
{
cur = top->_right;
}
}
cout << endl;
}
protected:
Node* _CreatTree(T* a, size_t n, const T& invalid, size_t& index)
{
Node* root = NULL;
if (index < n&&a[index] != invalid)
{
root = new Node(a[index]);
root->_left = _CreatTree(a, n, invalid, ++index);
root->_right = _CreatTree(a, n, invalid, ++index);
}
return root;
}
private:
Node* _root;
};