Binary Tree Zigzag Level Order Traversal (LeetCode) 层序遍历二叉树

时间:2022-06-16 20:55:56

题目描述:

Binary Tree Zigzag Level Order Traversal

AC Rate: 399/1474

My Submissions

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
queue<TreeNode *> qu;
qu.push(root);
qu.push(NULL); // flag for end of one level bool right2left = false;
vector<vector<int> > res; if(NULL==root) return res; vector<int> lev; // for nodes in one level while(1)
{
TreeNode *cur = qu.front();
qu.pop(); if(cur)
{
lev.push_back(cur->val);
if(cur->left) qu.push(cur->left);
if(cur->right) qu.push(cur->right);
}
else // end of one level
{
if(!right2left)
{
res.push_back(lev);
}
else
{
reverse(lev.begin(),lev.end());
res.push_back(lev);
}
right2left = !right2left; if(qu.size()==0) break; qu.push(NULL);
lev.clear();
}
}
return res;
}
};