【18】面试题23:分层打印二叉树

本文介绍了一种分层遍历二叉树的方法,通过使用队列实现从上至下、从左至右的节点打印。当遇到空节点时,提示二叉树为空。代码中定义了`PrintBinaryTree`类,并实现了`PritTree`方法,该方法首先检查根节点,然后将根节点入队,接着在循环中不断出队并打印节点,同时将左右子节点入队,直至队列为空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【1】题目

题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。例如输入图4.5中的二叉树,则依次打印出8、6、10、5、7、9、11

【2】思路

【3】代码


#pragma once
#ifndef PRINTBINARY_H
#define PRINTBINARY_H


struct BinaryNode
{
	int value;
	BinaryNode*   leftptr;
	BinaryNode*	  rightptr;
};


class PrintBinaryTree
{
	public:
	PrintBinaryTree();
	~PrintBinaryTree();
	
	//分层打印二叉树
	void PritTree(BinaryNode* pTreeRoot);
};

#endif // !PRINTBINARY_H
#include "pch.h"
#include "PrintBinaryTree.h"
#include<iostream>
#include<queue>

using namespace std;

PrintBinaryTree::PrintBinaryTree()
{

}

PrintBinaryTree::~PrintBinaryTree()
{

}

void PrintBinaryTree::PritTree(BinaryNode* pTreeRoot)
{
	//判断节点是否为空
	if (pTreeRoot->leftptr==nullptr||pTreeRoot->rightptr==nullptr)
	{
		cout << "binary tree is empty!!\n";
	}

	//开始遍历打印
	//建立队列存放每一个节点后的数据
	queue<BinaryNode*> myqueue;
	myqueue.push(pTreeRoot);
	while (myqueue.size()!=0)
	{
		BinaryNode* head = myqueue.front();
		myqueue.pop();
		printf("%d", head->value);
		if (head->leftptr)
		{
			myqueue.push(head->leftptr);
		}
		if (head->rightptr)
		{
			myqueue.push(head->rightptr);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值