题目:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

题目:
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。   
例如输入
  8
  / \
 6 10
/ \ / \
5 7 9 11

输出8 6 10 5 7 9 11。


解题思路:利用队列先进先出(FIFO)的性质,取出队首元素,输出队首节点元素,将节点的左右子节点加入队列,取出队首元素,重复上述操作,直到取出队列中所有元素。

#include <queue>
#include <iostream>
#include <string.h>
using namespace std;
struct BSTreeNode          //a node in the binary search tree (BST)
{
  int m_nValue;            //value of node
  BSTreeNode *m_pLeft;     // left child of node
  BSTreeNode *m_pRight;    // right child of node
};
queue<BSTreeNode*>P;
void BuildTree(BSTreeNode *&Node,int n)   //建立二叉树
{
	if(Node == NULL)
	{
		BSTreeNode *NewNode = new BSTreeNode();
		NewNode->m_nValue = n;
		NewNode->m_pLeft = NULL;
		NewNode->m_pRight = NULL;
		Node = NewNode;
	}
	else if(Node->m_nValue < n) 
	{
		BuildTree(Node->m_pRight,n);
	}
	else 
	{
		BuildTree(Node->m_pLeft,n);
	}
}
void OutPut()
{
	if(P.front() == NULL)
		return ;
	BSTreeNode *Node = P.front();
	cout<<P.front()->m_nValue<<" ";
	P.push(P.front()->m_pLeft);
	P.push(P.front()->m_pRight);
	P.pop();
	OutPut();
}
int main()
{
	BSTreeNode *Node = NULL;
	BuildTree(Node,8);
	BuildTree(Node,6);
	BuildTree(Node,10);
	BuildTree(Node,5);
	BuildTree(Node,7);
	BuildTree(Node,9);
	BuildTree(Node,11);
	P.push(Node);
	OutPut();
	cout<<endl;
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值