• [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
  • 相关阅读:
    Flask中的CBV以及正则表达式
    Flask中的渲染变量
    Flask中的request和response
    Flask中的cookie和session
    Flask的请求扩展
    [NOIP2000] 提高组 洛谷P1018 乘积最大
    [NOIP2000] 提高组 洛谷P1017 进制转换
    洛谷P2563 [AHOI2001]质数和分解
    巴蜀4384 -- 【模拟试题】作诗(Poetize)
    [NOIP1999] 提高组 洛谷P1016 旅行家的预算
  • 原文地址:https://www.cnblogs.com/freeneng/p/3207833.html
Copyright © 2020-2023  润新知