二叉树的层次遍历

二叉树从上到下遍历:

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

#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” 博客,转载请与作者联系!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值