标签:
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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
[Solution]
1 vector<vector<int> > zigzagLevelOrder(TreeNode *root) 2 { 3 vector<vector<int> > result; 4 vector<int> line; 5 queue<TreeNode *> qtree; 6 TreeNode *visit = root; 7 int current_level_size = 1, next_level_size = 0; 8 int level = 0; 9 10 if (visit != NULL) 11 qtree.push(visit); 12 while (!qtree.empty()) 13 { 14 visit = qtree.front(); 15 qtree.pop(); 16 current_level_size--; 17 line.push_back(visit->val); 18 19 if (visit->left != NULL) 20 { 21 qtree.push(visit->left); 22 next_level_size++; 23 } 24 if (visit->right != NULL) 25 { 26 qtree.push(visit->right); 27 next_level_size++; 28 } 29 if (current_level_size == 0) // all this level nodes are visited. 30 { 31 if (level & 0x01) 32 reverse(line.begin(), line.end()); 33 level++; 34 result.push_back(line); 35 line.clear(); 36 current_level_size = next_level_size; 37 next_level_size = 0; 38 } 39 } 40 41 return result; 42 }
leetcode 103. Binary Tree Zigzag Level Order Traversal
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4295404.html