之字形打印二叉树
(我以为跟此次遍历二叉树一样那么简单,发现人家这个题貌似比层次遍历高一个level)
思路:利用队列,队列中出一个元素,就把它的左右孩子带进去,不过先开始得设置一个标志位为false,表示他不是从左往右打印的,每一个层次遍历完,都改变falg的值,falg为false,那就翻转
/*
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;
if(pRoot==NULL)
return res;
queue<TreeNode*> que;
bool flag=false; //正向打印
que.push(pRoot);
while(que.size()!=0)
{
vector<int> v;
int len=que.size();
for(int i=0;i<len;i++)
{
TreeNode* tmp=que.front();
v.push_back(tmp->val);
que.pop();
if(tmp->left)
que.push(tmp->left);
if(tmp->right)
que.push(tmp->right);
}
if(flag) reverse(v.begin(),v.end());
flag=!flag;
res.push_back(v);
}
return res;
}
};