可以使用stack
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
stack<vector<TreeNode*>> st;
vector<vector<int>> vt;
if(root==NULL)
return vt;
vector<TreeNode*> v;
v.push_back(root);
st.push(v);
while(1)
{
v=st.top();
vector<TreeNode*> vs;
for(int i=0;i<v.size();i++)
{
if(v[i]->left)
vs.push_back(v[i]->left);
if(v[i]->right)
vs.push_back(v[i]->right);
}
if(vs.size()==0)
break;
st.push(vs);
}
while(!st.empty())
{
v=st.top();
st.pop();
vector<int> tmp;
for(int j=0;j<v.size();j++)
{
tmp.push_back(v[j]->val);
}
vt.push_back(tmp);
}
return vt;
}
};
2.使用queue
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> vec;
if(root==NULL)
return res;
vec.push(root);
while(!vec.empty())
{
queue<TreeNode*> tmp_vec;
vector<int> tmp_res;
while(!vec.empty())
{
TreeNode* node=vec.front();
tmp_res.push_back(node->val);
if(node->left)
tmp_vec.push(node->left);
if(node->right)
tmp_vec.push(node->right);
vec.pop();
}
res.push_back(tmp_res);
vec=tmp_vec;
}
reverse(res.begin(), res.end());
return res;
}
};