/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
vector<TreeNode*> tmp;
vector<vector<int>> ans;
void f(TreeNode* root) {
tmp.push_back(root);
int i=1;
while(!tmp.empty()) {
vector<TreeNode*> t;
vector<int> tt;
int flag = 0;
if(i==-1) {
for(int j=tmp.size()-1;j>=0;j--) {
if(tmp[j]!=NULL) {
flag = 1;
tt.push_back(tmp[j]->val);
}
}
}
for(int j=0;j<=tmp.size()-1;j++) {
if(tmp[j]!=NULL) {
t.push_back(tmp[j]->left);
t.push_back(tmp[j]->right);}
}
if(i==1) {
for(int j=0;j<=tmp.size()-1;j++) {
if(tmp[j]!=NULL) {
flag = 1;
tt.push_back(tmp[j]->val);
}
}
}
i=-1*i;
if(flag == 1)
ans.push_back(tt);
tmp = t;
}
}
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
ans.clear(); tmp.clear();
f(root);
return ans;
}
};
binary-tree-zigzag-level-order-traversal
最新推荐文章于 2020-03-25 17:26:06 发布