1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<vector<int>> Zigzaglevelorder (treenode*root) { -vector<int>Row; -vector<vector<int>>v; theQueue<treenode *>Q; - if(Root = =NULL) - returnv; - Q.push (root); +TreeNode *temp; - intLev =0; + while(!Q.empty ()) { A intSize =q.size (); at while(size--) { -temp =Q.front (); - Q.pop (); -Row.push_back (temp->val); - if(Temp->left! =NULL) { -Q.push (temp->Left ); in } - if(Temp->right! =NULL) { toQ.push (temp->Right ); + } - } the if(Lev%2) { * intn =row.size (); $ for(inti =0; I < n/2; i++) {Panax NotoginsengSwap (Row[i], row[n-i-1]); - } the } + v.push_back (row); Alev++; the row.clear (); + } - returnv; $ } $};
View Code
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]]
Analysis: and sequence traversal the same code, only need to add a few lines of code on the line ~ ~ ~ because the font to store this binary tree ~ ~ ~
So just when the number of rows is even, you need to do all the elements of the current row upside down ~ can be used stack can also be used to exchange the array 22 ~ ~ ~
You just need to invert the row array before you deposit the two-dimensional array vector<vector> V, and then push_back into v.
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<vector<int>> Zigzaglevelorder (treenode*root) { -vector<int>Row; -vector<vector<int>>v; theQueue<treenode *>Q; - if(Root = =NULL) - returnv; - Q.push (root); +TreeNode *temp; - intLev =0; + while(!Q.empty ()) { A intSize =q.size (); at while(size--) { -temp =Q.front (); - Q.pop (); -Row.push_back (temp->val); - if(Temp->left! =NULL) { -Q.push (temp->Left ); in } - if(Temp->right! =NULL) { toQ.push (temp->Right ); + } - } the if(Lev%2) { * intn =row.size (); $ for(inti =0; I < n/2; i++) {Panax NotoginsengSwap (Row[i], row[n-i-1]); - } the } + v.push_back (row); Alev++; the row.clear (); + } - returnv; $ } $};
View Code
Leetcode 103. Binary Tree Zigzag level Order traversal