zoukankan      html  css  js  c++  java
  • [Leetcode 80] 107 Binary Tree Level Order Traversal II

    Problem:

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    Analysis:

    This problem is an extension of the original level order traversal problem. The only extra thing need to do is to reverse the whole result vector before return.

    One thing to remember is that, after exit the while loop in the program, the last level's result is not yet push into the result vector. This operation cannot be omitted.

    Code:

     1 /**
     2  * Definition for binary tree
     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         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         vector<vector<int> > res;
    16         if (root == NULL)
    17             return res;
    18             
    19         queue<TreeNode *> q;
    20         q.push(root);
    21         
    22         TreeNode *sentl = new TreeNode(-1);
    23         sentl->left = NULL;
    24         sentl->right = NULL;
    25         q.push(sentl);
    26         
    27         TreeNode *tmp;
    28         vector<int> pres;
    29         while (q.size() !=1 ) {
    30             tmp = q.front();
    31             q.pop();
    32             
    33             if (tmp == sentl) {
    34                 res.push_back(pres);
    35                 pres.clear();
    36                 q.push(sentl);
    37             } else {
    38                 pres.push_back(tmp->val);
    39                 
    40                 if (tmp->left != NULL)
    41                     q.push(tmp->left);
    42                 
    43                 if (tmp->right != NULL)
    44                     q.push(tmp->right);
    45             }
    46         }
    47         res.push_back(pres);
    48         
    49         reverse(res.begin(), res.end());
    50         
    51         return res;
    52     }
    53 };
    View Code
  • 相关阅读:
    python之基础知识篇
    OpenGL 着色器管理类 Shader
    OpenGL 彩色三角形
    OpenGL 你好,三角形 练习一 二 三
    OpenGL 矩阵绘画
    OpenGL 第一个三角形!!!!
    OpenGL 读取,使用 .vert .frag 着色器 文件 C++
    C++ 一定要使用strcpy_s()函数 等来操作方法c_str()返回的指针
    OpenGL 入门指南(配置GLFW ,着色语言高亮,以及一些常见问题)
    汽车加工厂
  • 原文地址:https://www.cnblogs.com/freeneng/p/3207833.html
Copyright © 2011-2022 走看看