Topic Links:
http://www.lintcode.com/zh-cn/problem/binary-tree-zigzag-level-order-traversal/
Zigzag hierarchy traversal of two fork tree
Give a binary tree, return its node value of the zigzag level traversal (first from left to right, the next layer from right to left, between layers and layers alternately)
Sample Example
Give a binary tree {3,9,20,#,#,15,7}
,
3 / 9 / 7
Returns the hierarchical traversal of its jagged shape as:
[3], [20,9], [15,7]]
Ideas:
We simulate this process with a double-ended queue: It starts with a forward traversal, and 3 Push_front () into the queue Q to form Q[3]. Then we specify the forward traversal from the front of the queue to the element, the next layer of elements into the queue is placed in the back end of the queue, while the reverse traversal is the opposite, the only difference is the reverse traversal, the next layer of the Right child node (if any) first placed in the front of the queue.
Start Q[3] (take the number from the front end), and then the next layer is placed after the q[9,20] (from the back end to the number), 20 of the next layer is placed after the q[15,7,9], and then become q[15,7] (from the front end to the number), and finally get the result of the traversal.
Code implementation:
/** Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * TreeNode (i NT val) {* This->val = val; * This->left = This->right = NULL; *} *}*/ classSolution {/** * @param root:the root of binary tree. * @return: A List of lists of integer include * The zigzag level order traversal of its nodes ' values ' /c5>*/ Public: Vector<vector<int>> Zigzaglevelorder (TreeNode *root) { //Write your code herevector<vector<int>>VV; if(Root = NULL)returnVV; Deque<treenode *>Q; Q.push_back (root); BOOLDIR =true;//True indicates a left-to-right storage hierarchy traversal, otherwise right-to-left intlevelcnt =1;//number of nodes on the previous layer intcurlevelcnt =0;//number of nodes in the next layervector<int>v; while(!Q.empty ()) {TreeNode*cur; if(dir) {cur=Q.front (); Q.pop_front (); } Else{cur=Q.back (); Q.pop_back (); } if(dir) {if(cur->Left ) {Q.push_back (cur-Left ); ++curlevelcnt; } if(cur->Right ) {Q.push_back (cur-Right ); ++curlevelcnt; } } Else { if(cur->Right ) {Q.push_front (cur-Right ); ++curlevelcnt; } if(cur->Left ) {Q.push_front (cur-Left ); ++curlevelcnt; }} v.push_back (cur-val); --levelcnt; if(levelcnt = =0){//This floor is complete .Vv.push_back (v); V.clear (); Levelcnt=curlevelcnt; Curlevelcnt=0; Dir= !dir; } } returnVV; }};
Lintcode Two-fork tree zigzag hierarchy Traversal (double-ended queue)