zoukankan      html  css  js  c++  java
  • 剑指offer-面试题32-分行从上到下打印二叉树-二叉树遍历

    /*
    题目:
    	分行按层自上向下打印二叉树。
    */
    /*
    思路:
    	使用队列,将节点压入队列中,再弹出来,压入其左右子节点,循环,直到栈为空。
    	添加两个计数器,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);
    
    }
    

       

  • 相关阅读:
    pandas中的时间序列基础
    Python中的进程
    Pandas透视表和交叉表
    Pandas分组级运算和转换
    Python中的线程详解
    Pandas聚合
    Python面试题整理
    Pandas分组
    暑假集训 || 动态规划
    DFS || HDU 2181
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11938720.html
Copyright © 2011-2022 走看看