zoukankan      html  css  js  c++  java
  • leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历

    基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行下一个循环就可以了。

    C++代码:

     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>> levelOrder(TreeNode* root) {
    13         if(root==NULL) return {};
    14         queue<TreeNode*> q;
    15         TreeNode* front;
    16         q.push(root);
    17         vector<vector<int>> res;
    18         
    19         while(!q.empty()){
    20             vector<int> onelevel;
    21             for(int i=q.size();i>0;i--){
    22                 front=q.front();
    23                 q.pop();
    24                 if(front->left)
    25                     q.push(front->left);
    26                 if(front->right)
    27                     q.push(front->right);
    28                 onelevel.push_back(front->val);
    29             }
    30             res.push_back(onelevel);
    31         }
    32         return res;
    33     }
    34 };
  • 相关阅读:
    2013年10月17日 搬出来了
    如何与领导相处
    WEB系统开发
    C++ 常用术语(后续补充)
    C++ 构造函数放置默认转换explicit关键字(2)
    工作与生活
    C++类型转化分析(1)
    (一)win7下cocos2d-x 21 + vs2010
    为了生活
    iOS
  • 原文地址:https://www.cnblogs.com/joelwang/p/10332354.html
Copyright © 2011-2022 走看看