题解 | #从下到上打印二叉树#
从下到上打印二叉树
http://www.nowcoder.com/practice/ed982e032ff04d6a857b4cb4e6369d04
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrderBottom(TreeNode* root) {
// write code here
vector<vector<int>> res;
vector<int> ans;
if(!root)
return res;
ans.push_back(root->val);
res.push_back(ans);
queue<TreeNode*> cel;
if(root->left)
cel.push(root->left);
if(root->right)
cel.push(root->right);
int count = cel.size();
ans.clear();
while(cel.size()) {
auto r = cel.front();
cel.pop();
count--;
ans.push_back(r->val);
if(r->left)
cel.push(r->left);
if(r->right)
cel.push(r->right);
if(count == 0) {
count = cel.size();
res.push_back(ans);
ans.clear();
}
}
reverse(res.begin(), res.end());
return res;
}
};