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]]
The topic is still relatively simple, mainly is a level scan and then the process of flipping
Here is a bit like a sequence scan, in the sequence scan is mainly using a queue for storage node, and then read out the corresponding Val, here needs to return the type needs to be given by layer, so you need to use a vector to each layer of nodes to record
/** * 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>> Res; int flag= 0; vector<vector<int> > Zigzaglevelorder (TreeNode *root) {res.clear (); if (root = NULL) {return res; } vector<treenode*>pnode; Pnode.push_back (root); vector<int> tmp; Tmp.push_back (Root->val); Res.push_back (TMP); flag++; GetNode (Pnode); return res; } void GetNode (Vector<treenode*> &pnode) {if (Pnode.empty ()) {return; } vector<treenode*> Node; Vector<treenode*>::iterator it = Pnode.begin (); vector<int> tmp; for (; it! = Pnode.end (); it++) {TreeNode * root = *it; if (root->left) {Tmp.push_back (root->left->val); Node.push_back (Root->left); } if (root->right) {tmp.push_back (root->right->val); Node.push_back (Root->right); }} if (Tmp.empty ()) {return;//< No child node, can return} if (flag&1) { Reverse (Tmp.begin (), Tmp.end ()); } flag++; Res.push_back (TMP); GetNode (Node); }};
The main use of a vector flip operation
Also see a way to operate with a queue, where a null node is placed on the last side of each layer of operations to determine that the data for this layer has been solved
/** * 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> > result; Vector<int> temp; Result.clear (); if (root==null) return result; Queue<treenode *> ptemp; int flag=0; Ptemp.push (root); Ptemp.push (NULL); while (!ptemp.empty ()) {TreeNode *curnode=ptemp.front (); Ptemp.pop (); if (curnode!=null) {temp.push_back (curnode->val); if (curnode->left) Ptemp.push (curnode->left); if (curnode->right) Ptemp.push (curnode->right); } else {if (!temp.empty ()) { Ptemp.push (NULL); if (flag==1) {reverse (Temp.begin (), Temp.end ()); } result.push_back (temp); Flag=1-flag; Temp.clear (); }}} return result; }};
Leetcode-binary tree Zigzag level Order traversal two fork Tree Z-Scan