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
  • 相关阅读:
    Java的参数传递是「按值传递」还是「按引用传递」?
    算法08 五大查找之:二叉排序树(BSTree)
    算法07 五大查找之:索引查找
    算法06 五大查找之:二分查找
    Django rest_framework实现RESTful API
    jenkins + pipeline构建自动化部署
    jenkins部署.net平台自动化构建
    python实现编写windows服务
    iis部署python运行环境
    Jenkins执行批处理文件、powershell失败
  • 原文地址:https://www.cnblogs.com/freeneng/p/3207833.html
Copyright © 2011-2022 走看看