正常层序遍历后翻转输出
二叉树的之字形层序遍历
http://www.nowcoder.com/questionTerminal/47e1687126fa461e8a3aff8632aa5559
/** * 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) { // write code here if (!root) return {}; vector<vector<int> > ret; queue<TreeNode*> q; q.push(root); vector<int> tmp; while (!q.empty()) { tmp.clear(); int currentSize = q.size(); for (int i = 0; i < currentSize; i++) { TreeNode *node = q.front(); q.pop(); tmp.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } ret.push_back(tmp); } //层序遍历 //翻转Z型 for (int i = 0; i < ret.size(); i++) if (i & 1 != 0) reverse(ret[i].begin(), ret[i].end()); return ret; } };