题解 | #从下到上打印二叉树#
从下到上打印二叉树
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<>>
*/
void bfs(TreeNode* root,int t,vector<vector<int> >& res){
if(!root)return;
if(t==res.size()){
vector<int > tmp(1,root->val);
res.push_back(tmp);
}
else{
res[t].push_back(root->val);
}
bfs(root->left,t+1,res);
bfs(root->right,t+1,res);
return;
}
/*vector<vector<int> > levelOrderBottom(TreeNode* root) {
// write code here
vector<vector<int> > res;
bfs(root,0,res);
reverse(res.begin(),res.end());
return res;
}*/
vector<vector<int> > levelOrderBottom(TreeNode* root) {
// write code here
vector<vector<int> > res;
if(!root)return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int t=q.size();
vector<int> tmp;
while(t--){
TreeNode* node=q.front();
tmp.push_back(node->val);
if(node->left)q.push(node->left);
if(node->right)q.push(node->right);
q.pop();
}
res.push_back(tmp);
}
reverse(res.begin(),res.end());
return res;
}
};