标签:
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.
Analyse: The same as Binary Tree Level Order Traversal except that we need a boolean variable to determine whether the current level need reverse.
1. Recursion
Runtime: 4ms
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 13 vector<vector<int> >result; 14 zigzag(root, 0, true, result); 15 return result; 16 } 17 void zigzag(TreeNode* root, int level, bool l2r, vector<vector<int> >& result){ 18 if(!root) return; 19 if(level == result.size()) result.push_back(vector<int> ()); 20 21 if(l2r) result[level].push_back(root->val); 22 else result[level].insert(result[level].begin(), root->val); 23 24 zigzag(root->left, level + 1, !l2r, result); 25 zigzag(root->right, level + 1, !l2r, result); 26 } 27 };
2. Iteration
Runtime: 4ms.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 13 vector<vector<int> >result; 14 if(!root) return result; 15 queue<TreeNode* > qu; 16 qu.push(root); 17 bool l2r = false; 18 19 while(!qu.empty()){ 20 int n = qu.size(); 21 l2r = !l2r; 22 23 vector<int> level; 24 while(n--){ 25 TreeNode* temp = qu.front(); 26 qu.pop(); 27 28 if(l2r) level.push_back(temp->val); 29 else level.insert(level.begin(), temp->val); //if the boolean variable is not true, do reverse-sequence 30 31 if(temp->left) qu.push(temp->left); 32 if(temp->right) qu.push(temp->right); 33 } 34 result.push_back(level); 35 } 36 return result; 37 } 38 };
Binary Tree Zigzag Level Traversal
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4682132.html