二叉树的层序遍历Ⅱ-力扣
很简单的一道题,将前一道题的结果数组进行一次反转即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void order(TreeNode* cur, vector<vector<int>>& result, int depth){
if(cur == nullptr){
return;
}
if(result.size() == depth){
result.push_back(vector<int>());
}
result[depth].push_back(cur->val);
order(cur->left, result, depth + 1);
order(cur->right, result, depth + 1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
int depth = 0;
order(root, result, depth);
reverse(result.begin(), result.end());
return result;
}
};