To prove safety offer- face questions 32- branches are printed upside down binary - binary tree traversal

/*
topic:
	Branches binary printing press downwardly from the upper layer.
*/
/*
Ideas:
	Using the queue, the queue node into the press, and then pops up, which is pressed into the left and right child node, loop, until the stack is empty.
	Add two counters, current record number of nodes of the current line, next record number of nodes in the next line.
*/
#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);

}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11938720.html