题目:
从上往下打印出二叉树的每个结点,同一层的结点按照从左往右的顺序打印。
边界条件:
root为空
思路:
这其实是广度优先算法,要用到队列。
首先将root结点入队列。
当队列不为空时,下面一直循环。
取队列front的一个结点,输出其value,出队列。
将上一步取出的结点左结点入队列,然后右结点入队列。
重复上述过程。
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
struct BinaryTreeNode{
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
void printTreeByBFS(BinaryTreeNode *root)
{
if(root == NULL) return;
queue<BinaryTreeNode *> testQueue;
testQueue.push(root);
while (testQueue.size() != 0)
{
BinaryTreeNode *getFromQueue = testQueue.front();
testQueue.pop();//别忘了出队列操作
cout << getFromQueue->value << " ";
if (getFromQueue->left != NULL) testQueue.push(getFromQueue->left);
if (getFromQueue->right != NULL) testQueue.push(getFromQueue->right);
}
}
int main()
{
return 0;
}