2020年9月6日 星期日

LeetCode 107. Binary Tree Level Order Traversal II [Easy] [C++] 解題筆記

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]
]
想法:
    基本上直接用 BFS 走訪即可,最後輸出答案前再做 reverse 即可。
完整程式碼:
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if (root == nullptr) { return {}; }
        vector<vector<int>> res;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int q_size = q.size();
            vector<int> level(q_size);
            for (int i = 0; i < q_size; i++) {
                auto cur = q.front();
                q.pop();
                level[i] = cur->val;
                if (cur->left != nullptr) { q.push(cur->left); }
                if (cur->right != nullptr) { q.push(cur->right); }
            }
            res.emplace_back(level);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

沒有留言:

張貼留言