Untitled

 avatar
unknown
c_cpp
2 years ago
1.7 kB
4
Indexable
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ans;
            if(root == NULL) return ans;
            vector<int> subAns;
            queue<TreeNode*> q;
            q.push(root);
            q.push(NULL);
            while(!q.empty()) {
                TreeNode* front = q.front();
                q.pop();
                if(front == NULL) {
                    ans.push_back(subAns);
                    subAns = {};
                    if(q.size() == 0) break;
                    q.push(NULL);
                }
                else {
                    subAns.push_back(front->val);
                    if(front->left != NULL) q.push(front->left);
                    if(front->right != NULL) q.push(front->right);
                }
            }
            return ans;
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> answer = levelOrder(root);
        int counter = 0;
        for(int i = 0; i < answer.size(); i++) {
            if(counter&1) {
                reverse(answer[i].begin(), answer[i].end());
                counter++;
            }
            else {
                counter++;
            }
        }
        return answer;
    }
};
Editor is loading...