Binary Tree Zigzag Level Order Traversal -- LeetCode
2016-01-29 06:51
453 查看
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
return its zigzag level order traversal as:
思路:方法一是每一层都按照从左到右的顺序存入结果中,最后将所有奇数层(root为第0层)反转。时间复杂度O(n)
第二种方法:使用一个队列。依次遍历每一层。使用一个bool类型变量来记录当前层是需要从左向右还是从右向左。 每一层在队列中时都是从左向右的遍历顺序,如果当前层就是需要从左向右,则直接存入结果;否则,计算出该节点应该在的下标,并将它存入。
用队列遍历每一层的方法是,在进入每一层的最开始,当前队列中的节点全是该层的节点,此时队列中的元素数就是该层应该有的元素数。若该层需要从右向左遍历时,则每个元素在结果中的下标应该是size - i - 1。
该方法的时间复杂度同样是O(n).
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)
class Solution { public: void help(vector<vector<int> >& res, TreeNode* root, int depth) { if (!root) return; if (res.size() < depth + 1) res.push_back(vector<int>(1, root->val)); else res[depth].push_back(root->val); help(res, root->left, depth + 1); help(res, root->right, depth + 1); } vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int> > res; help(res, root, 0); for (int i = 1, n = res.size(); i < n; i += 2) reverse(res[i].begin(), res[i].end()); return res; } };
第二种方法:使用一个队列。依次遍历每一层。使用一个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; } };
相关文章推荐
- Verilog (二) multiplexer and decoder
- 【Leetcode】Kth Smallest Element in a BST
- (You Can Hack It, Architecture and Design) => { Dependency Injection; MEF sample; }
- GAE绑定域名
- 【Leetcode】Lowest Common Ancestor of a Binary Search Tree
- 如何让win7崩溃
- Leetcode 286. Walls and Gates
- Leetcode 296 Best Meeting Point
- [Regular Expressions] Introduction
- Leetcode 252 Meeting Rooms
- hdu 1806 RMQ
- hdu 1806 RMQ
- myeclipse 常规web项目创建
- Balanced Binary Tree -- LeetCode
- xfire客户端调用cxf服务端,一直报错
- how to get current path in qt
- 【Leetcode】Copy List with Random Pointer
- ASP.Net中无刷新执行Session身份验证
- LeetCode_40 Combination Sum II
- MSB&LSB与Endianness