LeetCode-103. Binary Tree Zigzag Level Order Traversal

网友投稿 696 2022-08-25

LeetCode-103. Binary Tree Zigzag Level Order Traversal

LeetCode-103. Binary Tree Zigzag Level Order Traversal

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

题解:

class Solution {public: vector> zigzagLevelOrder(TreeNode* root) { queue q; if (root == NULL) { return {}; } q.push(root); int cnt = 1; bool zigzag = false; vector v; vector> res; while(q.empty() == false) { if (cnt >= 0) { cnt--; TreeNode *t = q.front(); q.pop(); v.push_back(t->val); if (t->left != NULL) { q.push(t->left); } if (t->right != NULL) { q.push(t->right); } } if (cnt == 0) { if (zigzag == true) { reverse(v.begin(), v.end()); zigzag = false; } else if (zigzag == false) { zigzag = true; } res.push_back(v); v.clear(); cnt = q.size(); } } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-31. Next Permutation
下一篇:LeetCode-105. Construct Binary Tree from Preorder and Inorder Traversal
相关文章

 发表评论

暂时没有评论,来抢沙发吧~