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}
,
3 / 9 / 7
Return its zigzag level order traversal as:
[ 3], [20,9], [15,7]]
Hierarchy traversal, each layer joins a vector<int> cur
When traversing to a new layer, add cur to result and empty to prepare a new layer of data.
With Root as the No. 0 layer, the odd-numbered cur is reverse to the right and to the left before adding the result.
The above description covers two questions:
1, how to know the current on the first floor?
2, how to know the current into the new layer?
Solve:
1, in order to determine the number of layers traversed, set a node structure, which stores level. Level counts from 0 onwards.
Tier I nodes set the number of layers to i+1 when the child is in the queue.
2, set a variable lastlevel, record the number of layers of the last pop out node.
If the number of layers of the current pop out node is lastlevel+1, that is the new level.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */structnode{TreeNode*Tree; intLevel//Level%2==0--> left to right ; Level%2==1Node (treenode* root,intl): Tree (Root), level (L) {}};classSolution { Public: Vector<vector<int> > Zigzaglevelorder (TreeNode *root) {Vector<vector<int> >result; if(Root = =NULL)returnresult; Queue<Node*>Q; Vector<int>cur; Node* RootNode =NewNode (Root,0); intLastlevel =0;//If current level was bigger than lastlevel, means new levelQ.push (RootNode); while(!Q.empty ()) {Node* Front =Q.front (); Q.pop (); if(Front->level >lastlevel) {//New level if(lastlevel%2==1) Reverse (Cur.begin (), Cur.end ()); Result.push_back (cur); Cur.clear (); Lastlevel= front->Level ; } cur.push_back (Front->tree->val); if(front->tree->Left ) {Node* Leftnode =NewNode (Front->tree->left, front->level+1); Q.push (Leftnode); } if(front->tree->Right ) {Node* Rightnode =NewNode (Front->tree->right, front->level+1); Q.push (Rightnode); } } //Add last Level if(lastlevel%2==1) Reverse (Cur.begin (), Cur.end ()); Result.push_back (cur); returnresult; }};
Leetcode Binary Tree Zigzag level Order traversal