Topic:
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 / 7
Return its zigzag level order traversal as:
[ 3], [20,9], [15,7]]
Confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
idea: the solution and thinking of this problem is similar to binary Tree level Order traversal, but we need to set a flag to distinguish whether this line is a positive or reverse output array. We use the queue to store the nodes of the tree and use NULL to differentiate each row, remembering that when the queue is non-empty, each row is emptied, the level array is cleared, and null is added to distinguish the next line. We set the tag, tag true, to indicate the positive sequence, the output array from left to right, the tag to false, the reverse order, the output array from right to left.
Attention:
1. Remember that after each line is processed, when the queue is non-empty, the array level is emptied and null is added to the queue to differentiate the next line.
2. Usage of reverse
void reverse (Bidirectionaliterator first, Bidirectionaliterator last);
3. Use tag to differentiate the output sequence. Remember that each time you need tag to reverse, the next is the opposite direction.
if (tag) { ret.push_back (level); } else { reverse (level.begin (), Level.end ()); Ret.push_back (level); } tag =!tag;
Complexity: O (n), n is the number of nodes in the tree.
AC Code:
/** * Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * Tre Enode (int x): Val (x), left (null), right (NULL) {} *}; */class Solution {public:vector<vector<int> > Zigzaglevelorder (TreeNode *root) {VECTOR<VECTOR&L t;int>> ret; if (root = NULL) return ret; Vector<int> level; bool Tag = true; Queue<treenode*> Treeq; Treeq.push (root); Treeq.push (NULL); Differentiate between layered while (! Treeq.empty ()) {treenode* node = Treeq.front (); Treeq.pop (); if (node! = NULL) {level.push_back (node->val); if (node->left) Treeq.push (node->left); if (node->right) Treeq.push (node->right); } else {if (tag) {ret.push_back (level); } else {Reverse (Level.begin (), Level.end ()); Ret.push_back (level); } tag =!tag; if (! Treeq.empty ()) {level.clear (); Treeq.push (NULL); }}} return ret; }};
[C + +] leetcode:101 Binary Tree Zigzag level Order traversal