首页 > 其他 > 详细

二叉树的层次遍历

时间:2016-05-23 01:05:17      阅读:205      评论:0      收藏:0      [点我收藏+]

二叉树从上到下遍历:

利用栈,先将根节点压入栈中,出栈,遍历该节点的左孩子,右孩子,依次把该节点的右孩子,左孩子压入栈中。

#include<iostream>
#include<stack>
using namespace std;
struct BinaryTreeNode
{
	BinaryTreeNode(int value)
		:_value(value)
		,_left(NULL)
		,_right(NULL)
	{
	}
	int _value;
	BinaryTreeNode* _left;
	BinaryTreeNode* _right;
};
class BinaryTree
{
public:
	BinaryTree(int* a,int len)
	{
		int index=0;
		_root=_create(a,index,len);
	}
	void Pre()//前序遍历
	{
		PreOrder(_root);
	}
	void Floor_Print()//层次遍历
	{
		Floor(_root);
	}
private:
	BinaryTreeNode* _create(int* a,int &index,int len)
	{
		BinaryTreeNode* root=NULL;
		if(a[index]!=‘#‘&&index<len)
		{
			root=new BinaryTreeNode(a[index]);
			root->_left=_create(a,++index,len);
			root->_right=_create(a,++index,len);
		}
		return root;

	}
	void PreOrder(BinaryTreeNode* root)
	{
		if(root==NULL)
		{
			return;
		}
		cout<<root->_value<<"->";
		PreOrder(root->_left);
		PreOrder(root->_right);
	}
	void Floor(BinaryTreeNode* root)  //依次将根节点入栈,然后出栈,遍历节点的左孩子,右孩子,		                              然后将该节点的右孩子入栈,左孩子入栈。
	{
		if(root==NULL)
		{
			return;
		}
		stack<BinaryTreeNode*> s1;
		s1.push(root);
		cout<<root->_value<<"->";
		while(!s1.empty())
		{
			BinaryTreeNode* cur=s1.top();
			s1.pop();
			
			if(cur->_left)
			cout<<cur->_left->_value<<"->";
			if(cur->_right)
			cout<<cur->_right->_value<<"->";
			if(cur->_right)
			s1.push(cur->_right);
			if(cur->_left)
			s1.push(cur->_left);

		}
	}
private:
	BinaryTreeNode* _root;
};
int main()
{
	int a[]={1,2,3,‘#‘,‘#‘,4,‘#‘,‘#‘,5,6,‘#‘,7};
	BinaryTree b1(a,sizeof(a)/sizeof(a[0]));
	b1.Pre();
	cout<<endl;
	b1.Floor_Print();
	system("pause");
    return 0;
}


本文出自 “liveyoung” 博客,转载请与作者联系!

二叉树的层次遍历

原文:http://youngyoungla.blog.51cto.com/10697042/1776012

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!