题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
用flag做标志位,记录是从左到右还是从右到左。
/* 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 res; q.push(pRoot); bool flag = true; while(!q.empty()){ int size = q.size(); int i = 0; vector<int>tmp(size,0); while(i < size){ TreeNode* t = q.front(); if(flag)tmp[i] = t->val; else tmp[size - i - 1] = t->val; q.pop(); if(t->left)q.push(t->left); if(t->right)q.push(t->right); i++; } res.push_back(tmp); flag = !flag; } return res; } };