Binary Tree Zigzag Level Order Traversal
2013-05-28 15:33
281 查看
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:
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 vector<vector<int> > result; int line_cnt = 0; int next_line_cnt = 0; int line_no = 0; queue<TreeNode*> q; if (root == NULL) { return result; } q.push(root); line_cnt = 1; vector<int> line; TreeNode* t = NULL; while (!q.empty()) { t = q.front(); line.push_back(t->val); if (t->left) { q.push(t->left); ++next_line_cnt; } if (t->right) { q.push(t->right); ++next_line_cnt; } q.pop(); --line_cnt; if (0 == line_cnt) { ++line_no; if (line_no % 2 == 1) { result.push_back(line); } else { result.push_back(vector<int>(line.rbegin(), line.rend())); } line.clear(); line_cnt = next_line_cnt; next_line_cnt = 0; } } return result; } };
相关文章推荐
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- LeetCode | Binary Tree Zigzag Level Order Traversal
- [LeetCode-15]Binary Tree Zigzag Level Order Traversal
- [LeetCode] 015: Binary Tree Zigzag Level Order Traversal
- [leetcode 103]Binary Tree Zigzag Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- LeetCode Binary Tree Zigzag Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal (Tree, Queue; BFS)
- 【LeetCode】binary-tree-level-order-traversal i&ii&zigzag
- leedcode做题总结,题目Binary Tree Zigzag Level Order Traversal 2012/09/28
- Binary Tree Zigzag Level Order Traversal
- Leetcode#103 Binary Tree Zigzag Level Order Traversal
- 103. Binary Tree Zigzag Level Order Traversal
- leetcode-Binary Tree Zigzag Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- Lintcode71 Binary Tree Zigzag Level Order Traversal solution 题解
- 103. Binary Tree Zigzag Level Order Traversal
- LeetCode OJ:Binary Tree Zigzag Level Order Traversal