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<int>> levelOrderBottom(TreeNode* root) { // time: O(n); space: O(n)
    vector<vector<int> > res;
    if (!root) return res;
    vector<int> cur;
    queue<TreeNode*> q({root});
    while (!q.empty()) {
        int n = q.size();
        cur.clear();
        for (int i = 0; i < n; ++i) {
            TreeNode* t = q.front(); q.pop();
            cur.push_back(t->val);
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        res.push_back(cur);
    }
    reverse(res.begin(), res.end());
    return res;
}

Last updated

Was this helpful?