题目是102的变形,这里的处理就是改变了一下输出形式
/**
* 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 {
public:
int DepthOfTree(TreeNode* root) //求树的深度
{
if(!root) return 0;
int leftDepth = DepthOfTree(root->left);
int rightDepth = DepthOfTree(root->right);
return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
}
vector<vector<int> > result;
void init(int maxDepth)
{
for(int i=0; i<maxDepth; i++)
result.push_back(vector<int>());
}
void LevelOrderTraversal(TreeNode* root, int level, int maxDepth)
{
if(!root) return;
result[maxDepth-level-1].push_back(root->val);
LevelOrderTraversal(root->left, level+1, maxDepth);
LevelOrderTraversal(root->right, level+1, maxDepth);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
int depth = DepthOfTree(root);
init(depth);
LevelOrderTraversal(root, 0, depth);
return result;
}
};