简单、整洁。
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > ans; void bfs(TreeNode* r,int x) { cout<<r->val<<" "; if (ans.size() <= x) ans.resize(x + 1); if(r!=nullptr) ans[x].push_back(r->val); if(r->left!=nullptr) {bfs(r->left,x+1);} if(r->right!=nullptr) {bfs(r->right,x+1);} return ; } vector<vector<int> > levelOrderBottom(TreeNode* root) { // write code here bfs(root,0); reverse(ans.begin(),ans.end()); return ans; } };