给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/
9 20
/
15 7
返回其锯齿形的层次遍历为:
[
[3],
[20,9],
[15,7]
]
题目链接:http://www.lintcode.com/zh-cn/problem/binary-tree-zigzag-level-order-traversal/#
和层次遍历的道理相同,只不过我们需要设置一个bool变量,来判断在该行是正序遍历还是倒序遍历,维护一个双向队列。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: A list of lists of integer include
* the zigzag level order traversal of its nodes' values
*/
public:
vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
// write your code here
vector<vector<int>> result;
if(root == NULL) return result;
deque<TreeNode *> q;
q.push_back(root);
bool d = true;
int len;
while(!q.empty()) {
vector<int> res;
len = q.size();
TreeNode *temp;
while (len--) {
if (d) {
temp = q.front();
q.pop_front();
res.push_back(temp->val);
if (temp->left) q.push_back(temp->left);
if (temp->right) q.push_back(temp->right);
}
else {
temp = q.back();
q.pop_back();
res.push_back(temp->val);
if (temp->right) q.push_front(temp->right);
if (temp->left) q.push_front(temp->left);
}
}
result.push_back(res);
d = !d;
}
return result;
}
};