https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
Solution 1. Recursive level traversal. Need to add a {} to res to increase res.size() when starting a new level, otherwise res[level] causes index error.
void levelOrder(TreeNode* node, vector<vector<int>>& res, int level) {
if(!node) return;
if(level == res.size()) res.push_back({});
res[level].push_back(node->val);
levelOrder(node->left, res, level+1);
levelOrder(node->right, res, level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
levelOrder(root, res, 0);
reverse(res.begin(), res.end());
return res;
}
Solution 2. Push each level to a queue. Use nullptr as a separator between levels.
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
TreeNode* node;
q.push(root);
q.push(nullptr);
while(!q.empty()) {
vector<int> level;
while(node = q.front()){
q.pop();
level.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
q.pop();
q.push(nullptr);
if(level.empty()) break;
res.insert(res.begin(),level);
}
return res;
}
No comments:
Post a Comment