Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > res; if (root == NULL) return res; res.push_back(vector<int>(1, root->val)); vector<TreeNode*> pre_level(1, root); vector<TreeNode*> cur_level; bool l2r = true; while (!pre_level.empty()) { res.push_back(vector<int>()); int plen = pre_level.size(); TreeNode* node = NULL; for (int i=0; i<plen; i++) { node = pre_level[i]; if (node->left != NULL) { res.back().push_back(node->left->val); cur_level.push_back(node->left); } if (node->right != NULL) { res.back().push_back(node->right->val); cur_level.push_back(node->right); } } if (l2r) { reverse(res.back().begin(), res.back().end()); //reverse(cur_level.begin(), cur_level.end()); } pre_level.clear(); swap(pre_level, cur_level); if (pre_level.empty()) res.pop_back(); l2r = !l2r; } return res; } };
esay
第二轮:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int> > res; if (root == NULL) { return res; } vector<TreeNode*> last; vector<TreeNode*> next; res.push_back(vector<int>(1, root->val)); last.push_back(root); vector<int> curr; int level = 1; while (!last.empty()) { next.clear(); curr.clear(); for(TreeNode* node : last) { if (node->left != NULL) { next.push_back(node->left); curr.push_back(node->left->val); } if (node->right != NULL) { next.push_back(node->right); curr.push_back(node->right->val); } } if (curr.empty()) { break; } if (level++ & 0x1) { reverse(curr.begin(), curr.end()); } swap(next, last); res.push_back(curr); } return res; } };