The subject also belongs to the deformation of the hierarchical traverse, the difference is that the method of its traversal is alternating, forming a zigzag curve form, as follows:
The code is as follows:
1 structTreeNode {2 intVal;3treenode*Left ;4treenode*Right ;5TreeNode (intx): Val (x), left (null), right (null) {}6 };7 8 voidSwap (vector<int> &Ivec)9 {Ten inttemp =0; One intLen =ivec.size (); A for(inti =0; I < len/2; i + +) { -temp =ivec.at (i); -ivec.at (i) = ivec.at (len-1-i); theIvec.at (len-1-I.) =temp; - } - } - +Vector<vector <int> > Zigzaglevelorder (TreeNode *root) - { +vector<vector<int> >Tree_vector; Avector<int>Ivec; atQueue<treenode *>Tree_queue; - if(NULL = =root) - returnTree_vector; - - Tree_queue.push (root); - Tree_queue.push (NULL); in intNlevelcount =1; - while(true) { toTreeNode *ptemp =Tree_queue.front (); + Tree_queue.pop (); - if(Ptemp = =NULL) { the if(nlevelcount%2==0) {//if the num is odd, swap the Ivec; * Swap (Ivec); $ }Panax Notoginseng Tree_vector.push_back (Ivec); - ivec.clear (); the if(Tree_queue.empty ()) + Break; A Tree_queue.push (NULL); theNlevelcount + +; + } - Else { $Ivec.push_back (ptemp->val); $ if(ptemp->Left ) -Tree_queue.push (ptemp->Left ); - if(ptemp->Right ) theTree_queue.push (ptemp->Right ); - }Wuyi } the returnTree_vector; -}
Leetcode:binary Tree Zigzag level Order traversal