BFS solution is intuitive - here I will show a DFS based solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int height;
vector<vector<int>> ret; int getHeight(TreeNode*p)
{
if(!p) return ;
return max(getHeight(p->left), getHeight(p->right)) + ;
}
void go(TreeNode *p, int level)
{
if(!p) return;
ret[height - - level].push_back(p->val);
go(p->left, level + );
go(p->right, level + );
}
public:
vector<vector<int>> levelOrderBottom(TreeNode* root)
{
if(!root) return ret; height = getHeight(root);
ret.assign(height, vector<int>()); go(root, );
return ret;
}
};