Leetcode: Binary Tree Zigzag Level Order Traversal
代码:
class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > res; if(root == NULL) return res; vector<int> level; deque<TreeNode*> record; record.push_back(root); int cnt = 1, curcnt = 0; bool order = true; while(!record.empty()) { TreeNode *nxt = record.front(); record.pop_front(); level.push_back(nxt->val); if(nxt->left) { record.push_back(nxt->left); curcnt++; } if(nxt->right) { record.push_back(nxt->right); curcnt++; } cnt --; if(cnt == 0) { if(order) { // 正序 res.push_back(level); }else{ reverse(level.begin(), level.end()); res.push_back(level); } order = !order; level.clear(); cnt = curcnt; curcnt = 0; } } return res; } };