您的位置:首页 > 其它

LeetCode – Refresh – Binary Tree Zigzag Level Order Traversal

2015-03-18 09:12 375 查看
Made a stupid bug....... When reverse the vector, stop it at mid. Otherwise, it will swap back......

Mark!!!!!!!!

/**
* 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> > result;
vector<int> level;
if (!root) return result;
int current = 1, future = 0;
bool flag = false;
queue<TreeNode *> q;
q.push(root);
auto func = [](int &a, int &b) {int t = a; a = b; b = t;};
while (!q.empty()) {
TreeNode *tmp = q.front();
q.pop(), current--;
if (tmp->left) {
q.push(tmp->left);
future++;
}
if (tmp->right) {
q.push(tmp->right);
future++;
}
level.push_back(tmp->val);
if (!current) {
if (flag) {
for (int i = 0; i < level.size()/2; i++) {
func(level[i], level[level.size()-i-1]);
}
}
flag ^= 1;
result.push_back(level);
level.clear();
current = future;
future = 0;
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: