# 107.Binary Tree Level Order Traversal II

**<font color=red>难度Easy</font>**

## 刷题内容
> 原题连接

* https://leetcode.com/problems/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]
]
```
> 思路1
******- 时间复杂度: O(n)******- 空间复杂度: O(n)******

这是一道典型的BFS题目，第一种方法我用的是递归的方法，比较慢。

```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode* root) {
        if(!root)
        {
            vector<vector<int> > ret;
            return ret;
        }
        vector<int> v;
        v.push_back(root ->val);
        vector<vector<int> > temp1 = levelOrderBottom(root ->left);
        vector<vector<int> > temp2 = levelOrderBottom(root ->right);
        int pos1 = temp1.size() - 1;
        int pos2 = temp2.size() - 1;
        while(pos1 >= 0  && pos2 >= 0)
        {
            temp1[pos1].insert(temp1[pos1].end(),temp2[pos2].begin(),temp2[pos2].end());
            --pos1;
            --pos2;
        }
        if(pos2 >= 0)
        {
            auto pos = temp2.begin() + pos2 + 1;
            temp1.insert(temp1.begin(),temp2.begin(),pos);
        }
        temp1.push_back(v);
        return temp1;
    }
};
```
> 思路2
******- 时间复杂度: O(n)******- 空间复杂度: O(n)******

第二种改进的方法用的是类似栈的储存方式
```cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int> > ret;
        if(root != nullptr)
        {
            vector<TreeNode> v;
            v.push_back(*root);
            judge(v,ret);
        }
        return ret;
    }
    void judge(vector<TreeNode>& v,vector<vector<int> >& ret)
    {
        vector<TreeNode> v1;
        vector<int> v2;
        for(int i = 0;i < v.size();i++)
        {
            v2.push_back(v[i].val);
            if(v[i].left != nullptr)
                v1.push_back(*(v[i].left));
            if(v[i].right != nullptr)
                v1.push_back(*(v[i].right));
        }
        if(v1.size())
            judge(v1,ret);
        ret.push_back(v2);
    }
};
```