zoukankan      html  css  js  c++  java
  • leetcode 102. 二叉树的层次遍历

    给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

    例如:
    给定二叉树: [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    返回其层次遍历结果:

    [
      [3],
      [9,20],
      [15,7]
    ]

     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 
    11 class Solution {
    12 public:
    13     vector<vector<int>> levelOrder(TreeNode* root) {
    14         queue<TreeNode*> q;
    15         q.push(root);
    16         vector<vector<int>> ans;
    17         if(root == NULL) return ans;
    18         while(!q.empty()){
    19             queue<TreeNode*> qt;
    20             vector<int> t;
    21             while(!q.empty()){
    22                 TreeNode* temp = q.front();
    23                 q.pop();
    24                 t.push_back(temp->val);
    25                 if(temp->left) qt.push(temp->left);
    26                 if(temp->right) qt.push(temp->right);
    27             }
    28             ans.push_back(t);
    29             q = qt;
    30         }
    31         return ans;
    32     }
    33 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    看清爱情的本质,学会受伤。
    美股课堂:美国银行开户亲历记
    京JS 2013
    果皮移动
    果皮移动 移动电商!
    http://www.cutt.com/
    简网APP工场-服务介绍
    Get started
    中科院青年公寓
    c++ replaceAll
  • 原文地址:https://www.cnblogs.com/mr-stn/p/8978189.html
Copyright © 2011-2022 走看看