zoukankan      html  css  js  c++  java
  • 剑指offer之【从上往下打印二叉树】

    题目:

      从上往下打印二叉树

    链接:

      https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

    题目描述:

      从上往下打印出二叉树的每个节点,同层节点从左至右打印。

    思路:

      建立一个序列:对当前点的左右子节点进行扫描,非空则压入序列,然后对当且节点输入并弹出(只要序列不为空则一直进行此步骤)

    代码:

      

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 class Solution {
    11 public:
    12     vector<int> PrintFromTopToBottom(TreeNode* root){
    13         if(root == nullptr)
    14               return res;
    15         stk.push(root);
    16         while(!stk.empty()){
    17             TreeNode* temp = stk.front();
    18             if(temp->left != nullptr){
    19                 stk.push(temp->left);
    20             }
    21             if(temp->right != nullptr){
    22                 stk.push(temp->right);
    23             }
    24             res.push_back(temp->val);
    25             stk.pop();
    26         }
    27         return res;
    28     }
    29 private:
    30     vector<int> res;
    31     queue<TreeNode*> stk;
    32 };
  • 相关阅读:
    windows10安装vmware14教程
    MySQL变量的使用
    软考和软件设计师
    Java web加密之将应用从http换成https的方法
    cmd命令net和sc
    cmd命令 taskkill
    CSS系列:CSS的继承与层叠特性
    CSS系列:CSS选择器
    CSS系列:在HTML中引入CSS的方法
    Sql Server系列:索引维护
  • 原文地址:https://www.cnblogs.com/wangshujing/p/6936794.html
Copyright © 2011-2022 走看看