# 剑指offer之分行从上到下打印二叉树

## 1 题目

                  2
3    5
1  4  2  3 

2

3     5

1     4     2     3

## 2 分析

现在无非就是还要按照条件打印，第一次打印1个，然后第二次打印2个，第三次打印4个，我们可以这样，搞2个变量，第一个变量表示这行还没有打印的个数，另外一个变量是下列需要打印的个数，如果这一行还没有打印的个数是0了，我们就把下列需要打印值个数赋值给它，然后下一列变量的个数变量赋值为0.

## 3 代码实现

#include <iostream>
#include <queue>

using namespace std;

typedef struct Node
{
int value;
struct Node* left;
struct Node* right;
} Node;

{
{
std::cout << "head is NULL" << std::endl;
return;
}
std::queue<Node *> queue;
//下一列需要打印节点的个数
int next_print_count = 0;
//当前这一列还需要打印节点的个数
int has_print_count = 1;
while(queue.size())
{
Node *node = queue.front();
std::cout << node->value << "\t";
if (node->left)
{
queue.push(node->left);
next_print_count++;
}
if (node->right)
{
queue.push(node->right);
next_print_count++;
}
queue.pop();
has_print_count--;
if (has_print_count == 0)
{
has_print_count = next_print_count;
next_print_count = 0;
std::cout << std::endl;
}
}
}

int main()
{
/*              2
*           3    5
*         1  4  2  3
*
*/
Node head1, node1, node2, node3, node4, node5, node6;
node1.value = 3;
node2.value = 5;
node3.value = 1;
node4.value = 4;
node5.value = 2;
node6.value = 3;

node1.left = &node3;
node1.right = &node4;

node2.left = &node5;
node2.right = &node6;

node3.left = NULL;
node3.right = NULL;
node4.left = NULL;
node4.right = NULL;
node5.left = NULL;
node5.right = NULL;
node6.left = NULL;
node6.right = NULL;

return 0;
}



## 4 运行结果

2
3       5
1       4       2       3