您的位置:首页 > 其它

Binary Tree Zigzag Level Order Traversal

2013-05-28 15:33 281 查看
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]
]

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
int line_cnt = 0;
int next_line_cnt = 0;
int line_no = 0;
queue<TreeNode*> q;
if (root == NULL) {
return result;
}
q.push(root);
line_cnt = 1;
vector<int> line;
TreeNode* t = NULL;
while (!q.empty()) {
t = q.front();
line.push_back(t->val);
if (t->left) {
q.push(t->left);
++next_line_cnt;
}
if (t->right) {
q.push(t->right);
++next_line_cnt;
}
q.pop();
--line_cnt;
if (0 == line_cnt) {
++line_no;
if (line_no % 2 == 1) {
result.push_back(line);
} else {
result.push_back(vector<int>(line.rbegin(), line.rend()));
}
line.clear();
line_cnt = next_line_cnt;
next_line_cnt = 0;
}
}
return result;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: