二叉树的之字形层序遍历
二叉树的之字形层序遍历
http://www.nowcoder.com/questionTerminal/47e1687126fa461e8a3aff8632aa5559
C++ BFS 改造,加一个翻转
因为是之字形,所以偶数行flag=1是从左到右遍历,奇数行是flag=0,逆序遍历。
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > zigzagLevelOrder(TreeNode* root) { vector<vector<int> >res; queue<TreeNode*> que; if(root==nullptr) return res; que.push(root); int flag = 1; while(!que.empty()){ int size = que.size(); vector<int> temp; for(int i=0;i<size;i++){ TreeNode* node = que.front(); que.pop(); if(node->left) que.push(node->left); if(node->right) que.push(node->right); if(flag){ temp.push_back(node->val); }else{ temp.insert(temp.begin(), node->val); } } flag = 1-flag; res.push_back(temp); } return res; } };