和104題目相似开睡,區(qū)別在于本題樹的層數(shù)由低到高存儲。
代碼:
class Solution {
public:
? ? vector<vector<int>> result;
void trval(TreeNode* t,int level)
{
? ? int maxlevel=result.size();
? ? if(maxlevel<level)
? ? {
? ? ? ? vector<int>temp;
? ? ? ? temp.push_back(t->val);
? ? ? ? result.insert(result.begin(),temp);
? ? }
? ? else
? ? {
? ? ? ? result[maxlevel-level].push_back(t->val);
? ? }
? ? if(t->left!=NULL)
? ? ? ? trval(t->left, level+1);
? ? if(t->right!=NULL)
? ? ? ? trval(t->right, level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root){
? ? if(root!=NULL)
? ? ? ? trval(root, 1);
? ? return result;
}
};