"title"
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]]
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"Code One"
/********************************** Date: 2014-12-09* sjf0115* question number: Binary Tree Zigzag level Order traversal* Source: HTTPS ://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/* Results: ac* Source: leetcode* Summary: ******************* /#include <iostream> #include <malloc.h> #include <stack> #include <vector># Include <queue>using namespace std;struct TreeNode {int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (NULL) {}};class solution {public:vector<vector<int> > Zigzagle Velorder (TreeNode *root) {vector<int> level; Vector<vector<int> > levels; if (root = NULL) {return levels; } queue<treenode*> CURQ,NEXTQ; Stack<treenode*> curs,nexts; Index layer int index = 1; Into the queue curq.push (root); Hierarchical traversal while (!curq.empty () | | |!curs.empty ()) {//Current layer traversal while (!curq.empty () | |!curs.empty ()) {TreeNode *p,*q; The odd layer uses the queue to store if (index & 1) {p = Curq.front (); Curq.pop (); The first even tier stores the next layer of nodes with stacks//left dial hand tree if (p->left) {Nexts.push (P->left) ; Used to traverse the node Nextq.push (P->left) from left to right; }//Right subtree if (p->right) {Nexts.push (p->right); Used to traverse Nextq.push (P->right) from left to right; }}//Even layer with stack storage else{p = curs.top (); Curs.pop (); The storage node is traversed from left to right through q = Curq.front (); Curq.pop (); The odd layer uses the queue to store the next layer of nodes//left dial hand tree if (q->left) { Nextq.push (Q->left); }//Right subtree if (q->right) {Nextq.push (q->right); }} level.push_back (P->val); } index++; Levels.push_back (level); Level.clear (); Swap (NEXTQ,CURQ); Swap (nexts,curs); }//while return levels; }};//creates a two-fork-tree int createbtree (treenode* &t) {char data) in order sequence; Enter the value of the node in the binary tree in order of precedence (one character), and ' # ' indicates the empty tree cin>>data; if (data = = ' # ') {T = NULL; } else{T = (treenode*) malloc (sizeof (TreeNode)); Generate root node T->val = data-' 0 '; Constructs left subtree Createbtree (t->left); Construct right subtree Createbtree (t->right); } return 0;} int main () {solution solution; treenode* root (0); Createbtree (root); vector<vector<int> > VECs = solution.zigzaglevelorder (root); for (int i = 0;i< Vecs.size (); i++) {for (int j = 0;j < Vecs[i].size (); j + +) {cout<<vecs[i][j]; } cout<<endl; }}
"code two"
[Leetcode] Binary Tree Zigzag level Order traversal