32.3 按之字形顺序打印二叉树
作者:互联网
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
struct nd{
TreeNode* node;
int deep;
nd(TreeNode* node, int deep): node(node), deep(deep){}
};
vector<vector<int> > Print(TreeNode* pRoot) {
if(pRoot == nullptr) return vector<vector<int>>{};
vector<vector<int>> ans;
ans.push_back(vector<int>{});
queue<nd> q;
int currentDeep=1;
q.push(nd(pRoot, 1));
while(!q.empty()){
auto ndnow = q.front();
q.pop();
if(ndnow.deep > currentDeep){
ans.push_back(vector<int>{});
currentDeep = ndnow.deep;
}
ans.back().push_back(ndnow.node->val);
if(ndnow.node->left){
q.push(nd(ndnow.node->left, ndnow.deep+1));
}
if(ndnow.node->right){
q.push(nd(ndnow.node->right, ndnow.deep+1));
}
}
for(int i=0;i<ans.size();++i){
if(i&1){
reverse(ans[i].begin(), ans[i].end());
}
}
return ans;
}
};
标签:node,之字形,TreeNode,int,deep,二叉树,push,32.3,ndnow 来源: https://www.cnblogs.com/N3ptuner/p/14588491.html