树节点是以数据作为底层存储结构来存放的,在遍历结点的时候,分别采用了递归和非递归的方法。
#include <cstdio>
#include <iostream>
#include <vector>
#include <stack>
using namespace std ;
struct node
{
int loc , key ,rchild ,lchild ;
node ( int l , int k ):loc(l) , key(k) ,lchild (-1 ) , rchild (-1)
{}
node ( int l , int k , int ll , int r )
{
loc = l ;
key = k ;
lchild = ll ;
rchild = r ;
}
} ;
typedef node *tree ;
typedef node treeNode ;
treeNode *T[100] ;
int root = -1 ;
void visitTreeRecur( treeNode* t[] , int k )
{
if ( k == -1 )
return ;
else
{
cout<<"node loc: " <<t[k]->loc<<"node key: "<<t[k]->key<<endl ;
visitTreeRecur(t , t[k]->lchild) ;
visitTreeRecur(t , t[k]->rchild ) ;
}
}
void InOrderNoRecur( treeNode *t [] , int root )
{
if ( root == -1 )
return ;
else
{
int x = root ;
stack<int> s ;
while ( (x!= -1) || !s.empty() )
{
if ( x != -1 )
{
s.push(x) ;
x = t[x]->lchild ;
}
else
{
x = s.top () ;
s.pop () ;
cout<<"node loc :"<<t[x]->loc <<" node key :"<<t[x]->key <<endl ;
x = t[x]->rchild ;
}
}
}
}
void PreOrderNonRecur ( treeNode *t [] , int root )
{
if ( root == -1 )
return ;
else
{
stack<int> s ;
int temp = root ;
while ( (temp != -1 ) || !s.empty() )
{
if ( temp != -1 )
{
cout<<" node loc :" <<t[temp]->loc <<" node key : " <<t[temp]->key <<endl ;
s.push(temp) ;
temp = t[temp]->lchild ;
}
else
{
temp = s.top () ;
s.pop () ;
temp = t[temp]->rchild ;
}
}
}
}
void initTree ()
{
T[1] = new treeNode(1 , 12, 7 , 3 ) ;
T[2] = new treeNode (2, 15 , 8 , -1) ;
T[3] = new treeNode(3, 4, 10 , -1 ) ;
T[4] = new treeNode (4 , 4 , 5 , 9 ) ;
T[5] = new treeNode (5 , 2 , -1 , -1) ;
T[6] = new treeNode (6 , 18 , 1 , 4) ;
T[7] = new treeNode (7 , 7 , -1 , -1 ) ;
T[8] = new treeNode (8 , 14 , 6 , 2 ) ;
T[9] = new treeNode (9 , 21 , -1 , -1 ) ;
T[10] = new treeNode (10 , 5 , -1 , -1 ) ;
root = 6 ;
PreOrderNonRecur(T , root ) ;
InOrderNoRecur(T , root ) ;
visitTreeRecur ( T , root ) ;
}
void main ( void )
{
initTree () ;
system("pause") ;
}
//coding me