/*
题目:
	分行按层自上向下打印二叉树。
*/
/*
思路:
	使用队列,将节点压入队列中,再弹出来,压入其左右子节点,循环,直到栈为空。
	添加两个计数器,current记录当前行的节点数,next记录下一行的节点数。
*/
#include<iostream>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stdio.h>
#include<vector>
#include<stack>
#include<queue>

using namespace std;

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};

void PrintFromTopToBottom(TreeNode* root){
    if(root == nullptr) return;

    deque<TreeNode*> myQueue;
    myQueue.push_back(root);
    TreeNode *temp;
    int current = 1;
    int next = 0;


    while(!myQueue.empty()){
       temp = myQueue.front();
       myQueue.pop_front();
       cout<<temp->val<<" ";
       current--;


       if(temp->left != nullptr){
            myQueue.push_back(temp->left);
            next++;
       }
       if(temp->right != nullptr){
            myQueue.push_back(temp->right);
            next++;
       }
       if(current == 0){
            cout<<endl;
            current = next;
            next = 0;
       }
    }

}

int main(){
    TreeNode* node1 = new TreeNode(1);
    TreeNode* node2 = new TreeNode(2);
    TreeNode* node3 = new TreeNode(3);
    TreeNode* node4 = new TreeNode(4);
    TreeNode* node5 = new TreeNode(5);
    TreeNode* node6 = new TreeNode(6);
    node1->left = node2;
    node1->right = node3;
    node2->left = node4;
    node3->left = node5;
    node3->right = node6;

    PrintFromTopToBottom(node1);

}

   

01-10 15:28