zoukankan      html  css  js  c++  java
  • leetcode-107. Binary Tree Level Order Traversal II

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

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    思路:
    首先定义一个vector<vector<TreeNode*>> temp来保存二叉树的层次遍历结果,然后将temp中的层次中节点的值倒序赋值给vector<vector<int>> result。

    accepted code:
     1 /**
     2  * Definition for a binary tree node.
     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>> result;
    14         vector<vector<TreeNode*>> temp;
    15         if(root==nullptr)
    16         return result;
    17         vector<TreeNode*> tk;
    18         tk.push_back(root);
    19         temp.push_back(tk);
    20         int i=0;
    21         while(temp[i].size()>0)
    22         {
    23             tk.clear();
    24             for(int j=0;j<temp[i].size();j++)
    25             {
    26                 if(temp[i][j]->left!=nullptr)
    27                 tk.push_back(temp[i][j]->left);
    28                 if(temp[i][j]->right!=nullptr)
    29                 tk.push_back(temp[i][j]->right);
    30             }
    31             temp.push_back(tk);
    32             i++;
    33         }
    34         vector<int> num;
    35         for(int i=temp.size()-2;i>=0;i--)
    36         {
    37             for(int j=0;j<temp[i].size();j++)
    38             {
    39                 num.push_back(temp[i][j]->val);
    40             }
    41             result.push_back(num);
    42             num.clear();
    43         }
    44         return result;
    45     }
    46 };

     
  • 相关阅读:
    00:Java简单了解
    QQ空间相册照片批量导出
    Git基本操作
    【有钱的大佬看过来】Java开发学习大纲
    默认端口号走一波
    获取“今日头条”西瓜视频
    CentOS 下源码安装LAMP环境
    书写是为了更好的思考
    U盘安装Ubuntu 14.04 LTS正式版 出现如下的提示,不能继续,如何操作?
    U盘安装Ubuntu 14.04 LTS正式版
  • 原文地址:https://www.cnblogs.com/hongyang/p/6417676.html
Copyright © 2011-2022 走看看