//创建树、遍历树、线索树
/*
typedef struct Node {
char value;
struct Node * lchild;
struct Node * rchild;
}BT_Node , *BT_Pointer;
void create_BT( BT_Pointer & T ) {
char c;
c = getchar();
if( c == '^' ) {
T = NULL;
}
else {
T = ( BT_Node * ) malloc ( sizeof( BT_Node ) );
T -> value = c;
create_BT( T -> lchild );
create_BT( T -> rchild );
}
}
void rec_pre_trav( const BT_Pointer T ) {
if( T != NULL ) {
cout << T -> value;
rec_pre_trav( T -> lchild );
rec_pre_trav( T -> rchild );
}
}
void rec_in_trav( const BT_Pointer T ) {
if( T != NULL ) {
rec_in_trav( T -> lchild );
cout << T -> value;
rec_in_trav( T -> rchild );
}
}
void rec_pos_trav( const BT_Pointer T ) {
if( T != NULL ) {
rec_pos_trav( T -> lchild );
rec_pos_trav( T -> rchild );
cout << T -> value;
}
}
void visit( const BT_Pointer p ) {
cout << p -> value;
}
void non_rec_pre_trav( const BT_Pointer T ) {
if( T == NULL ) {
return;
}
stack<BT_Pointer> s;
BT_Pointer p = T;
//注意下面两个条件
//仅仅( ! s.empty() )一个判断条件是不可以的,因为树根出栈之后,栈就空了,但是右子树还没有遍历
//此时p指向树根的右子树根节点
while( ( ! s.empty() ) || ( p != NULL ) ) {
//有左子树,就一直入栈。
//空树是不会入栈的
if( p != NULL ) {
s.push( p );
visit( p );
p = p -> lchild;
}
//没有左子树
else {
//出栈
p = s.top();
s.pop();
p = p -> rchild;
}
}
}
void non_rec_in_trav( const BT_Pointer T ){
if( T == NULL ) {
return;
}
stack<BT_Pointer> s;
BT_Pointer p = T;
while( ( ! s.empty() ) || ( p != NULL ) ) {
if( p != NULL ) {
s.push( p );
p = p -> lchild;
}
else{
p = s.top();
s.pop();
visit( p );
p = p -> rchild;
}
}
}
void non_rec_pos_trav( BT_Pointer T ) {
BT_Pointer p = T;
BT_Pointer stack[ 30 ];
int num = 0;
BT_Pointer have_visited=NULL;
while( NULL != p || num > 0 ) {
while( NULL != p ) {
stack[ num ++ ] = p;
p = p -> lchild;
}
p = stack[ num - 1 ];
//如果右子树为空,或者右子树是上一个访问的结点
if( NULL == p -> lchild || have_visited == p -> rchild ) {
visit( p );
num --;
have_visited = p;
p = NULL;
}
else {
p = p -> rchild;
}
}
}
//层次遍历,也可以在队列元素中增加一个int项用来标记层次
void level_trav( BT_Pointer T ) {
if( T == NULL ) {
return;
}
queue< BT_Pointer > q;
BT_Pointer cur = T;
//level_end 指向每层的最后节点
BT_Pointer level_end = T;
cur = T;
q.push( cur );
while( ! q.empty() ) {
cur = q.front();
q.pop();
visit( cur );
if( cur -> lchild != NULL ) {
q.push( cur -> lchild );
}
if( cur -> rchild != NULL ) {
q.push( cur -> rchild );
}
if( cur == level_end ) {
if( cur -> lchild != NULL ) {
level_end = cur;
}
if( cur -> rchild != NULL ) {
level_end = cur;
}
}
}
}
int main() {
BT_Pointer root = NULL;
cout << "建一棵二叉树:" << endl;
create_BT( root );
cout << "\n递归先序遍历:" << endl;
rec_pre_trav( root );
cout << "\n递归中序遍历:" << endl;
rec_in_trav( root );
cout << "\n递归后序遍历:" << endl;
rec_pos_trav( root );
cout << "\n非递归先序遍历:" << endl;
non_rec_pre_trav( root );
cout << "\n非递归中序遍历:" << endl;
non_rec_in_trav( root );
cout << "\n非递归后序遍历:" << endl;
non_rec_pos_trav( root );
cout << "\n层次遍历" << endl;
level_trav( root );
cout << endl;
}
*/
/*
abd^^e^^cf^^g^^
*/
树的遍历
最新推荐文章于 2023-03-14 17:04:32 发布