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] ]
要注意读取的顺序,是折线。每次都应该按照不同的顺序。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > re; vector<vector <TreeNode *> > t; vector<vector<int> > zigzagLevelOrder(TreeNode *root) { if( root != NULL) { vector<int> ve; ve.push_back(root->val); vector <TreeNode *> tr; tr.push_back(root->right); tr.push_back(root->left); re.push_back(ve); t.push_back(tr); get(0); } return re; } void get(int n) { vector<int> ve; vector <TreeNode *> tr; if(n%2 == 0) { vector<TreeNode *> tt; for(int i = 0 ; i < t[n].size();i++) { if(t[n][i] != NULL) { ve.push_back(t[n][i]->val); tt.push_back(t[n][i]->right); tt.push_back(t[n][i]->left); } } for(int i = tt.size()-1;i>=0;i--) tr.push_back(tt[i]); } else{ vector<TreeNode *> tt; for(int i = 0 ; i < t[n].size();i++) { if(t[n][i] != NULL) { ve.push_back(t[n][i]->val); tt.push_back(t[n][i]->left); tt.push_back(t[n][i]->right); } } for(int i = tt.size()-1;i>=0;i--) tr.push_back(tt[i]); } if(ve.size()==0)return; re.push_back(ve); t.push_back(tr); get(n+1); return ; } };