题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
queue<TreeNode*> q;
if(!pRoot)
return {};
bool flag = true;
q.push(pRoot);
while(!q.empty()){
int l = q.size();
vector<int> out(l);
for(int i=0; i<l; i++){
TreeNode* t = q.front();
q.pop();
int idx = flag ? i : (l - 1 - i);
out[idx] = t->val;
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
flag = !flag;
res.push_back(out);
}
return res;
}
};
https://www.cnblogs.com/grandyang/p/4297009.html

查看5道真题和解析
联想公司福利 1500人发布