[c++]基于数组的二叉树遍历

16 篇文章 0 订阅

树节点是以数据作为底层存储结构来存放的,在遍历结点的时候,分别采用了递归和非递归的方法。


#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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值