问题:
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] ]分析:
这道题给人一上来的感觉像是BFS,如果是BFS那么大家的第一印象就是使用queue。但这道题不能用queue,而应该用stack。原因是这样的:比如我们来看第二行,它应该是从右向左。如果我们使用queue的话,那么20会先进入queue。由于queue是先进先出,所以出queue的时候也是20先。而这就错了,因为下一个level是从左到右了,那么应该先出9,然后是9的左边child和9的右边child;然后才应该出20,20的左边child和20的右边child。下面这段代码中,使用了两个stack,一个current,一个next。current是保存当前level的nodes。如果current level是从左到右,那么就把child按照从左到右的顺序推进next。由于stack是先进后出,所以出来的时候,也就自然变成了从右到左。
代码:
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
stack<TreeNode *> current;
stack<TreeNode *> next;
vector<vector<int> > result;
if (!root) return result;
current.push(root);
bool leftToRight = true;
vector<int> level;
while (!current.empty()) {
TreeNode *temp = current.top();
current.pop();
level.push_back(temp->val);
if (leftToRight) {
if (temp->left)
next.push(temp->left);
if (temp->right)
next.push(temp->right);
}
else {
if (temp->right)
next.push(temp->right);
if (temp->left)
next.push(temp->left);
}
if (current.empty()) {
result.push_back(level);
leftToRight = !leftToRight;
swap(current, next);
level.clear();
}
}
return result;
}
};