题目链接:103. 二叉树的锯齿形层次遍历
题解:
同样是二叉树层序遍历!
题目简述:
给定一个二叉树进行层序遍历,但是要保证左右,右左顺序来回交替遍历!
题解:
**思路:**和上一题一模一样,多了一个条件,即当层数(从0开始)为奇数时,将遍历得到的vector
反转一次即可!
时间复杂度:O(n)
AC代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; if(!root) return res; queue<TreeNode*> q; q.push(root); int k = 0; while(q.size()){ vector<int> level; int len = q.size(); while(len --){ auto t = q.front(); q.pop(); level.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } if(k++ % 2) reverse(level.begin(), level.end()); res.push_back(level); } return res; } };
|