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

    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

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

        3
       / 
      9  20
        /  
       15   7
    

    返回其自底向上的层次遍历为:

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

     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 #include<algorithm>
    11 class Solution {
    12 public:
    13     vector<vector<int>> levelOrderBottom(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         reverse(ans.begin(), ans.end());
    32         return ans;
    33     }
    34 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    堆排序
    jdk8 永久代变更
    oracle 区分大小写遇到的坑
    日志统计分析
    zookeeper 服务挂掉重启后,dubbo 服务是不会自动重新注册上的
    代码质量管理
    快速排序算法
    python flask 项目结构
    项目架构
    JS中的循环---最全的循环总结
  • 原文地址:https://www.cnblogs.com/mr-stn/p/8978197.html
Copyright © 2011-2022 走看看