请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
层次遍历加上判断奇偶改变方向就行
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> res; if(pRoot == NULL) return res; queue<TreeNode*> que; que.push(pRoot); bool even = false; //是否为偶数行 while(!que.empty()){ //que非空循环,为空则终止循环 vector<int> vec; const int size = que.size(); //每次队列中被压入的节点数量,1,2,4... for(int i=0; i<size; ++i){ TreeNode* tmp = que.front(); //取出队列的首元素 que.pop(); //弹出队列第一个元素 vec.push_back(tmp->val); //将值压入vec中 if(tmp->left != NULL) //先压左孩子,再压右孩子 que.push(tmp->left); if(tmp->right != NULL) que.push(tmp->right); } if(even) //如果是偶数行,翻转 std::reverse(vec.begin(), vec.end()); res.push_back(vec); even = !even; } return res; } };