# 107. Binary Tree Level Order Traversal II (Easy)

## 1.問題

* 給予一個binary tree, 回傳一個bottom-up level order traversal的node's序列 (例如, 從左到右, 從leaf到root的方向層層排列)

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LOSWpDeKKzRSEn0doCN%2F-LOShm2t0QGHWAh94R9w%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-10%20%E4%B8%8B%E5%8D%887.22.35.png?alt=media\&token=be0a2861-956c-4322-a532-6bd0f6ae4a63)

## 2.想法

* 可用level-order traversal, 廣度優先搜尋(BFS)的概念:
  * 1.先將root node放入一開始的queue
  * 2.queue當前中的每一個元素若有子樹的, 則加入queue中 (等待下一次)
* 與Binary Tree Level Order Traversal 的解法相同, 但是改為從vector的底部insert

## 3.程式碼

```
/**
 * 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>> v;
        if (!root) {
            return v;
        }
        queue<TreeNode*> q;
        vector<int> vTemp;
        vTemp.push_back(root->val);
        v.insert(v.begin(), vTemp);
        q.push(root);
        
        while (!q.empty()){
            vector<int> vTemp;
            int size = q.size();
            for(int i = 0 ; i < size; i++){
                TreeNode* node = q.front();
                q.pop();
                if (node->left){
                    vTemp.push_back(node->left->val);
                    q.push(node->left);
                }
                if (node->right){
                    vTemp.push_back(node->right->val);
                    q.push(node->right);
                }
            }
            if (!vTemp.empty()){
                v.insert(v.begin(), vTemp);
            }
        }
        return v;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LH2YQTdpFVmQad9eBw5%2F-LH2a09h4UjV3ftaDw3t%2F2018071003.jpg?alt=media\&token=b03d181a-521b-4b9d-b1d3-14d025eb346c)
