先序遍历
迭代 基于定义
Stack<BinNodePosi(T)> S;
if ( x ) S.push ( x );
while ( !S.empty() ) {
x = S.pop(); visit ( x->data );
if ( HasRChild ( *x ) ) S.push ( x->rc );
if ( HasLChild ( *x ) ) S.push ( x->lc );
}
迭代 基于路径
template <typename T, typename VST>
static void visitAlongVine ( BinNodePosi(T) x, VST& visit, Stack<BinNodePosi(T)>& S ) {
while ( x ) {
visit ( x->data );
S.push ( x->rc );
x = x->lc;
}
}
template <typename T, typename VST>
void travPre_I2 ( BinNodePosi(T) x, VST& visit ) {
Stack<BinNodePosi(T)> S;
while ( true ) {
visitAlongVine ( x, visit, S );
if ( S.empty() ) break;
x = S.pop();
}
}

递归 基于定义
template <typename T, typename VST>
void travPre_R ( BinNodePosi(T) x, VST& visit ) {
if ( !x ) return;
visit ( x->data );
travPre_R ( x->lc, visit );
travPre_R ( x->rc, visit );
}
中序遍历
迭代 基于路径
template <typename T>
static void goAlongVine ( BinNodePosi(T) x, Stack<BinNodePosi(T)>& S ) {
while ( x ) { S.push ( x ); x = x->lc; }
}
template <typename T, typename VST>
void travIn_I1 ( BinNodePosi(T) x, VST& visit ) {
Stack<BinNodePosi(T)> S;
while ( true ) {
goAlongVine ( x, S );
if ( S.empty() ) break;
x = S.pop(); visit ( x->data );
x = x->rc;
}
}



递归 基于定义
template <typename T, typename VST>
void travIn_R ( BinNodePosi(T) x, VST& visit ) {
if ( !x ) return;
travIn_R ( x->lc, visit );
visit ( x->data );
travIn_R ( x->rc, visit );
}
后序遍历
迭代 基于路径
template <typename T>
static void gotoLeftmostLeaf ( Stack<BinNodePosi(T)>& S ) {
while ( BinNodePosi(T) x = S.top() )
if ( HasLChild ( *x ) ) {
if ( HasRChild ( *x ) ) S.push ( x->rc );
S.push ( x->lc );
} else
S.push ( x->rc );
S.pop();
}
template <typename T, typename VST>
void travPost_I ( BinNodePosi(T) x, VST& visit ) {
Stack<BinNodePosi(T)> S;
if ( x ) S.push ( x );
while ( !S.empty() ) {
if ( S.top() != x->parent )
gotoLeftmostLeaf ( S );
x = S.pop(); visit ( x->data );
}
}


递归 基于定义
template <typename T, typename VST>
void travPost_R ( BinNodePosi(T) x, VST& visit ) {
if ( !x ) return;
travPost_R ( x->lc, visit );
travPost_R ( x->rc, visit );
visit ( x->data );
}
层次遍历 迭代
template <typename T> template <typename VST>
void BinNode<T>::travLevel ( VST& visit ) {
Queue<BinNodePosi(T)> Q;
Q.enqueue ( this );
while ( !Q.empty() ) {
BinNodePosi(T) x = Q.dequeue();
visit ( x->data );
if ( HasLChild ( *x ) ) Q.enqueue ( x->lc );
if ( HasRChild ( *x ) ) Q.enqueue ( x->rc );
}
}
