给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
1条回答 默认 最新
关注
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()){ vector<int> vec; const int size = que.size(); for(int i=0; i<size; ++i){ TreeNode* tmp = que.front(); que.pop(); vec.push_back(tmp->val); 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; } };
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报