1.题目描述
103. Binary Tree Zigzag Level Order Traversal
Medium
68746FavoriteShare
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] ]
需要逐层依次从左到右再从右到左遍历二叉树。比如第一层从左到右,第二层就从右到左,第三层再从左到右,以此类推。
2.解题思路
主要原理还是广度优先搜索。
用两个栈实现这个过程。两个栈分别记为S1,S2。S1把栈内结点的下一层结点压入S2内,S2把栈内结点的下一层压入S1内,两者交替进行完成层次遍历。入S1的顺序是右结点,左结点;入S2的顺序是左结点,右结点。
以题目所给例子说明。每次栈内情况是:(排前面表示先入栈)
S1 【3】 【7,15】
S2 【9,20】
出栈时候读取对应数值,就完成了题目要求的左右交替层次遍历。
3.实现代码
/**
* 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>> V;
if (root==NULL)
return V;
stack<TreeNode*> S1, S2;
S1.push(root);
while (!S1.empty() || !S2.empty()) {
vector<int> v;
if (!S1.empty()) {
while (!S1.empty()) {
if (S1.top()->left)
S2.push(S1.top()->left);
if (S1.top()->right)
S2.push(S1.top()->right);
v.push_back(S1.top()->val);
S1.pop();
}
}
else if (!S2.empty()) {
while (!S2.empty()) {
if (S2.top()->right)
S1.push(S2.top()->right);
if (S2.top()->left)
S1.push(S2.top()->left);
v.push_back(S2.top()->val);
S2.pop();
}
}
V.push_back(v);
}
return V;
}
};