剑指OFFER 按之字形顺序打印二叉树
作者:互联网
剑指OFFER 按之字形顺序打印二叉树
套用 剑指OFFER 把二叉树打印成多行
的代码,然后翻转一下奇数行即可
/*
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) {
if(pRoot==NULL)return vector<vector<int> >();
queue<pair<TreeNode*,int> > que;//结点,层数
vector<vector<int> > res;//返回的结果
map<int,vector<int> >m;//层数--该层的所有结点
que.push(pair<TreeNode*,int>(pRoot,0));
while(!que.empty())
{
pair<TreeNode*,int> p = que.front();
que.pop();
m[p.second].push_back(p.first->val);
if(p.first->left!=NULL){
que.push(pair<TreeNode*,int>(p.first->left,p.second+1));
}
if(p.first->right!=NULL){
que.push(pair<TreeNode*,int>(p.first->right,p.second+1));
}
}
auto it = m.begin();
while(it != m.end())
{
res.push_back(it->second);
it++;
}
for(int i=0;i<res.size();i++)
{
if(i%2!=0)reverse(res[i].begin(),res[i].end());
}
return res;
}
};
标签:之字形,TreeNode,OFFER,second,que,二叉树,push,NULL,first 来源: https://www.cnblogs.com/virgildevil/p/12227899.html