Easy understand with c++,


  • -1
    K

    '''
    class Solution {
    public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> result;
    if(root==NULL) return result;
    queue<TreeNode*> q;
    int flag=1;
    q.push(root);
    vector<int> tep1;
    vector<int> tep2;
    while(!q.empty()){
    int si=q.size();
    while(si>0){
    TreeNode* tem=q.front();
    q.pop();
    tep1.push_back(tem->val);
    if(tem->left) q.push(tem->left);
    if(tem->right) q.push(tem->right);
    si--;
    }
    if(flag%2==0){
    for(int i=tep1.size()-1;i>=0;i--)
    tep2.push_back(tep1[i]);
    result.push_back(tep2);
    tep2.clear();
    tep1.clear();
    flag++;
    }else{
    result.push_back(tep1);
    tep1.clear();
    flag++;
    }
    }
    return result;
    }
    };
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.