• LeetCode OJ


    题目:

    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],
    ]

    解题思路:

    广度优先遍历,然后对结果进行翻转。

    代码:

     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         vector<vector<int> > ans;
    14         if (root == NULL) return ans;
    15         queue<TreeNode*> one;
    16         queue<TreeNode*> another;
    17         vector<int> cur_ans;
    18         TreeNode* cur_node;
    19         
    20         one.push(root);
    21         
    22         while (!one.empty() || !another.empty()) {
    23             if (!one.empty()) {
    24                 while (!one.empty()) {
    25                     cur_node = one.front();
    26                     one.pop();
    27                     cur_ans.push_back(cur_node->val);
    28                     if (cur_node->left) another.push(cur_node->left);
    29                     if (cur_node->right) another.push(cur_node->right);
    30                 }
    31                 ans.push_back(cur_ans);
    32                 cur_ans.clear();
    33             }
    34             if (!another.empty()) {
    35                 while (!another.empty()) {
    36                     cur_node = another.front();
    37                     another.pop();
    38                     cur_ans.push_back(cur_node->val);
    39                     if (cur_node->left) one.push(cur_node->left);
    40                     if (cur_node->right) one.push(cur_node->right);
    41                 }
    42                 ans.push_back(cur_ans);
    43                 cur_ans.clear();
    44             }
    45         }
    46         reverse(ans.begin(), ans.end());
    47         return ans;
    48     }
    49 };
  • 相关阅读:
    【2021-03-31】人生十三信条
    【2021-03-30】证明自己是人类忠实的朋友
    【2021-03-29】万物本是无序
    缀点成线
    1比特与2比特字符
    Solution -「LOCAL」「cov. 牛客多校 2020 第三场 I」礼物
    Solution -「HNOI 2007」「洛谷 P3185」分裂游戏
    Solution -「CF 1372E」Omkar and Last Floor
    Solution -「POJ 3710」Christmas Game
    Solution -「CF 1380F」Strange Addition
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3728207.html
Copyright © 2020-2023  润新知