二叉树递归遍历的时候,将其分为根、左子树、右子树三个部分。
其非递归遍历,也是分为三个部分,通过数据结构“栈”的入栈出栈操作以及其先入后出的特性,实现其遍历。
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;
};