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] ]
思路:方法一是每一层都按照从左到右的顺序存入结果中,最后将所有奇数层(root为第0层)反转。时间复杂度O(n)
1 class Solution { 2 public: 3 void help(vector<vector<int> >& res, TreeNode* root, int depth) 4 { 5 if (!root) return; 6 if (res.size() < depth + 1) 7 res.push_back(vector<int>(1, root->val)); 8 else res[depth].push_back(root->val); 9 help(res, root->left, depth + 1); 10 help(res, root->right, depth + 1); 11 } 12 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 13 vector<vector<int> > res; 14 help(res, root, 0); 15 for (int i = 1, n = res.size(); i < n; i += 2) 16 reverse(res[i].begin(), res[i].end()); 17 return res; 18 } 19 };
第二种方法:使用一个队列。依次遍历每一层。使用一个bool类型变量来记录当前层是需要从左向右还是从右向左。 每一层在队列中时都是从左向右的遍历顺序,如果当前层就是需要从左向右,则直接存入结果;否则,计算出该节点应该在的下标,并将它存入。
用队列遍历每一层的方法是,在进入每一层的最开始,当前队列中的节点全是该层的节点,此时队列中的元素数就是该层应该有的元素数。若该层需要从右向左遍历时,则每个元素在结果中的下标应该是size - i - 1。
该方法的时间复杂度同样是O(n).
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int> > res; if (!root) return res; queue<TreeNode *> q; q.push(root); bool LoR = true; while (!q.empty()) { int size = q.size(); vector<int> cand(size); for (int i = 0; i < size; i++) { int index = LoR ? i : size - i - 1; TreeNode* cur = q.front(); q.pop(); cand[index] = cur->val; if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); } res.push_back(cand); LoR = !LoR; } return res; } };
时间: 2024-12-22 21:54:40