# leetcode-Binary Tree Zigzag Level Order Traversal

708人阅读 评论(0)

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]
]


confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2   3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> > ret;

if (root == NULL)
return ret;

vector<int> nodes;

queue<TreeNode*> q;
TreeNode *nodePtr;
// levelNodesNum: the number of nodes in next level to traverse
int levelNodesNum = 1, nums, i;
int zz = 0;   // If 1, from left to right, or, from right to left

q.push(root);
nodes.push_back(root->val);
ret.push_back(nodes);

while (!q.empty()) {
i = 0;
nums = 0;
nodes.clear();

// Traverse the nodes of the same level, and push the nodes of next level
while (i < levelNodesNum) {
nodePtr = q.front();
if (nodePtr->left != NULL) {
q.push(nodePtr->left);
nodes.push_back(nodePtr->left->val);
++nums;
}
if (nodePtr->right != NULL) {
q.push(nodePtr->right);
nodes.push_back(nodePtr->right->val);
++nums;
}
q.pop();
++i;
}

levelNodesNum = nums;  // Update the number of nodes of the next level

if (nodes.empty()) {
break;
}

if (zz) {
ret.push_back(nodes);
zz = 0;
} else {
reverse(nodes.begin(), nodes.end());   // Right to left
ret.push_back(nodes);
zz = 1;
}
}

return ret;
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：69921次
• 积分：1262
• 等级：
• 排名：千里之外
• 原创：56篇
• 转载：1篇
• 译文：0篇
• 评论：44条
评论排行
最新评论