题解 | #二叉树层序遍历 ii#先层序遍历,再倒置即可
二叉树层序遍历 ii
https://www.nowcoder.com/practice/d8566e765c8142b78438c133822b5118
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrderBottom(TreeNode* root) { if(root==nullptr) return vector<vector<int>>{}; vector<vector<int>> arr; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int n=q.size(); vector<int> level; for(int i=0;i<n;i++){ TreeNode* node=q.front(); q.pop(); level.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } arr.push_back(level); } reverse(arr.begin(),arr.end()); return arr; } };