Binary Tree Zigzag level Order traversal
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},
Return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
Analysis
Assuming after traversing the 1st level, nodes in queue is {9, 20, 8},
And we are going to traverse 2nd level, which was even line and should print value from right to left [8, 20, 9].
We know there is 3 nodes in the current queue,
So the vector for this level in final result should is of size 3.
Then, the queue [i], goes to, Vector[queue.size ()-1-i] i.e.
The ith node in current queue should is placed in (Queue.size ()-1-i) position on vector for.
For example, for node (9), it's index in the queue is 0, so it's index in vector should be (3-1-0) = 2.
Code
vector<vector<int> >Zigzaglevelorder (treenode* root) {if(Root = NULL) {return vector<vector<int> >(); } vector<vector<int> >Result queue<TreeNode*>Nodesqueue; Nodesqueue.push (root);BOOLLeftToRight =true; while(!nodesqueue.empty ()) {intSize = Nodesqueue.size (); vector<int>row (size); for(inti =0; i < size; i++) {treenode* node = Nodesqueue.front (); Nodesqueue.pop ();//Find position to fill node ' s value intindex = (lefttoright)? I: (Size-1-i); Row[index] = node->val;if(Node->left) {Nodesqueue.push (node->left); }if(Node->right) {Nodesqueue.push (node->right); } }// after this levelLeftToRight =!lefttoright; Result.push_back (row); }returnResult;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode:binary Tree Zigzag level Order traversal