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 20 / 15 7
Return its zigzag level order traversal as:
[ [3], [20,9], [15,7]]
Idea: Using the sequence traversal, through the queue, sequentially traverse each layer, if the number of layers is even, then the number of the layer is flipped, using the vector's reverse function.
Code (c + +):
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: vector<vector<int>>Zigzaglevelorder (treenode* root) { vector<vector<int> >Resif(!root)returnRes vector<int>Nums queue<treenode *>Que TreeNode *p = root; Que.push (P);intLevel =0;//Curent level while(!que.empty ()) {Nums.resize (0); Level + =1;intQuesize = Que.size (); for(inti =0; i < quesize; i++) {p = Que.front (); Nums.push_back (P->val); Que.pop ();if(p->left) Que.push (p->left);if(p->right) Que.push (p->right); }if(Level%2==0) Reverse (Nums.begin (), Nums.end ()); Res.push_back (Nums); }returnRes }};
Leetcode[103]-binary Tree Zigzag level Order traversal