首页 > 代码库 > travel the binary tree by level 3 ( from down to top and from right to left every level )

travel the binary tree by level 3 ( from down to top and from right to left every level )

travel the binary tree by level 3 ( from down to top )

个人信息:就读于燕大本科软件工程专业 目前大三;

本人博客:google搜索“cqs_2012”即可;

个人爱好:酷爱数据结构和算法,希望将来从事算法工作为人民作出自己的贡献;

博客内容:travel the binary tree by level 3 ( from down to top )

博客时间:2014-5-3;

编程语言:C++ ;

编程坏境:Windows 7 专业版 x64;

编程工具:vs2008 32位编译器;

制图工具:office 2010 ppt;

硬件信息:7G-3 笔记本;


my words

I think paper and pen is better than computer. 

problem

travel the binary tree by level 3 ( from down to top and from left to right ) and class it  by level

eg: the binary tree follows


travelling result follows:

 

my solution

travel the binary tree by level( from down to top and from right to left ), and class it by level.

tool with queue and stack, travel the tree by queue and visit it by stack.


void _TravelByLevel(node * T)
{
	queue<node *> Q;
	stack<node *> S;
	cout<<"travel start"<<endl;
	if(T != NULL)
	{
		Q.push(T);
		Q.push(NULL);
		node * p;

		while(! Q.empty())
		{

			// first action
			p = Q.front();
			Q.pop();
			//_Visit(p);
			S.push(p);

			// second action
			if(p->left != NULL)
				Q.push(p->left);
			if(p->right != NULL)
				Q.push(p->right);

			// third action
			if(Q.front() == NULL)
			{
				Q.pop();
				if(Q.empty())
					break;
				S.push(NULL);
				Q.push(NULL);
				//cout<<"level"<<endl;
			}
		}

		while(! S.empty())
		{
			if(S.top() != NULL)
				_Visit(S.top());
			else cout<<"level"<<endl;
			S.pop();
		}
	}
	cout<<"travel over"<<endl;
	
}

my code

test.cpp

#include<iostream>
#include<queue>
#include<stack>
using namespace std;



class node
{
public:
    int data ;
    node * left ;
    node * right ;
    node()
	{
        data = http://www.mamicode.com/0 ;>