题目解析:(链接)
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.
解题思路:
递归版:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 13 travel(root, 1); 14 bool flag = false; 15 for (auto &i : result) { 16 if (flag) { 17 reverse(i.begin(), i.end()); 18 } 19 flag = !flag; 20 } 21 22 return result; 23 } 24 25 void travel(TreeNode *root, int level) { 26 if (!root) return; 27 28 if (level > result.size()) { 29 result.push_back(vector<int>()); 30 } 31 32 result[level - 1].push_back(root->val); 33 travel(root->left, level + 1); 34 travel(root->right, level + 1); 35 } 36 private: 37 vector<vector<int>> result; 38 };
迭代版:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 13 vector<vector<int>> result; 14 if (!root) return result; 15 16 queue<TreeNode *> current, next; 17 vector<int> level; 18 current.push(root); 19 while (!current.empty()) { 20 while(!current.empty()) { 21 TreeNode *tmp = current.front(); 22 current.pop(); 23 level.push_back(tmp->val); 24 25 if (tmp->left != nullptr) next.push(tmp->left); 26 if (tmp->right != nullptr) next.push(tmp->right); 27 } 28 29 result.push_back(level); 30 level.clear(); 31 swap(current, next); 32 } 33 34 bool flag = false; 35 for (auto &i : result) { 36 if (flag) { 37 reverse(i.begin(), i.end()); 38 } 39 flag = !flag; 40 } 41 42 return result; 43 } 44 };