【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);
}
}
}