zoukankan      html  css  js  c++  java
  • Binary Tree Level Order Traversal II

    同样,使用两个队列进行层间循环和层内循环。最后使用一个栈进行转置。

    PS:

    特别注意的是,对于vector的使用,在赋值的阶段会发生内存报错的情况:

    vector<int> vec1;

    vec1[0]=1

    直接使用下标赋值是错误的,应使用的是push_back()函数进行数值添加。

    而,在调用已经赋值的变量时,可以使用下标,如:
    int num=vec1[0];

    一定注意!!

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int>> levelOrderBottom(TreeNode* root) {
    13         vector<vector<int>> res;
    14 
    15         stack<vector<int>> st;
    16         
    17         if(root==NULL)
    18             return res;
    19         TreeNode * temp;
    20         queue<TreeNode *> q;
    21         q.push(root);
    22         while(!q.empty())  //层间循环
    23         {
    24             queue<TreeNode *> q2;
    25             vector<int> level;
    26             while(!q.empty())  //层内的节点循环
    27             {
    28                 temp=q.front();
    29                 q.pop();
    30                 level.push_back(temp->val);
    31                 if(temp->left!=NULL)
    32                     q2.push(temp->left);
    33                 if(temp->right!=NULL)
    34                     q2.push(temp->right);
    35             }
    36             q=q2;
    37             st.push(level);
    38         }
    39         while(!st.empty())
    40         {
    41             res.push_back(st.top());
    42             st.pop();
    43         }
    44         return res;
    45      }
    46 };
  • 相关阅读:
    为django项目创建虚拟环境
    linux下安装python
    使用scrapy-crawlSpider 爬取tencent 招聘
    linux基础3
    Scrapy
    scrapy-Redis 分布式爬虫
    scrapy-redis(一)
    Linux中文件上传使用rz
    centos 7 安装nginx
    MySQL 5.7 zip 文件安装过程
  • 原文地址:https://www.cnblogs.com/aguai1992/p/4629522.html
Copyright © 2011-2022 走看看