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
  • 相关阅读:
    禁止root远程登录解决办法
    小肥羊
    高级英语
    通用做饭general
    2021/03/10,创新与毁灭
    pandaExpressRound2
    2021/03/08,经历建立的你
    系统与细节
    报税
    事业portfolio
  • 原文地址:https://www.cnblogs.com/freeneng/p/3207833.html
Copyright © 2011-2022 走看看