題目
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,null,null,15,7],
3
/
9 20
/
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
解題之法
/**
* 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) return res;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
s1.push(root);
vector<int> out;
while (!s1.empty() || !s2.empty()) {
while (!s1.empty()) {
TreeNode *cur = s1.top();
s1.pop();
out.push_back(cur->val);
if (cur->left) s2.push(cur->left);
if (cur->right) s2.push(cur->right);
}
if (!out.empty()) res.push_back(out);
out.clear();
while (!s2.empty()) {
TreeNode *cur = s2.top();
s2.pop();
out.push_back(cur->val);
if (cur->right) s1.push(cur->right);
if (cur->left) s1.push(cur->left);
}
if (!out.empty()) res.push_back(out);
out.clear();
}
return res;
}
};
分析
這道二叉樹的之字形層序遍歷是之前那道[LeetCode] Binary Tree Level Order Traversal 二叉樹層序遍歷的變形,不同之處在于一行是從左到右遍歷,下一行是從右往左遍歷,交叉往返的之字形的層序遍歷。根據其特點我們用到棧的后進先出的特點,這道題我們維護兩個棧,相鄰兩行分別存到兩個棧中,進棧的順序也不相同,一個棧是先進左子結點然后右子節點,另一個棧是先進右子節點然后左子結點,這樣出棧的順序就是我們想要的之字形了。
比如對于題干中的那個例子:
3
/
9 20
/
15 7
我們來看每一層兩個棧s1, s2的情況:
s1: 3
s2:
s1:
s2: 9 20
s1: 7 15
s2: