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] ]
在level的基础上加一个bool变量来记录是否轮到left_toright.
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 traversal(root,1,result,true); 15 return result; 16 } 17 18 void traversal(TreeNode *node,int level,vector<vector<int>> &result,bool left_toright) 19 { 20 21 if(node==NULL) return; 22 if(level>result.size()) 23 result.push_back(vector<int>()); //不可以缺少 24 if(left_toright) 25 { 26 result[level-1].push_back(node->val); 27 } 28 else{ 29 result[level-1].insert(result[level-1].begin(),node->val); 30 } 31 32 traversal(node->left,level+1,result,!left_toright); 33 traversal(node->right,level+1,result,!left_toright); 34 35 36 } 37 38 };