方法1:
/** * 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: vector<vector<int>> levelOrderBottom(TreeNode* root) { if(!root) return {}; vector<vector<int>> res; queue<TreeNode*> qu; stack<vector<int>> st; qu.push(root); while(!qu.empty()) { int num = qu.size(); vector<int> temp; while(num--) { auto p = qu.front(); qu.pop(); temp.push_back(p->val); if(p->left) qu.push(p->left); if(p->right) qu.push(p->right); } st.push(std::move(temp)); } while(!st.empty()) { res.push_back(st.top()); st.pop(); } return res; } };