Untitled

 avatar
unknown
plain_text
2 years ago
3.0 kB
5
Indexable
/*
// Definition for TreeNode
class TreeNode {
public:
    long val;
    TreeNode* left;
    TreeNode* right;
    TreeNode* next;
    TreeNode (long x) {
        val = x;
        left = NULL;
        right = NULL;
        next = NULL;
    }
*/

class BinaryTreeZigzagLevelOrderTraversal {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        queue<TreeNode*>q;
        q.push(root);
        vector<int>temp;
        vector<vector<int>>ans;
        if(root == NULL){
            return ans;
        }
        temp.push_back(root->val);
        ans.push_back(temp);
        temp.clear();
        int level=2;
        while(!q.empty()) {
            int sz=q.size();
            while(sz--) {
                // this needs to be moved inside this while loop
                TreeNode*ptr=q.front();
                q.pop();

                if(ptr->left!=NULL) {
                    q.push(ptr->left);
                    temp.push_back(ptr->left->val);
                }
                if(ptr->right!=NULL) {
                    q.push(ptr->right);
                    temp.push_back(ptr->right->val);
                }
            }
            
            // for the last level there will be no new addition that's why it will have no elements
            if(temp.size() == 0) {
                break;
            }
            if(level%2!=0) {
                ans.push_back(temp);
            }
            else {
                reverse(temp.begin(),temp.end());
                ans.push_back(temp);
            }
            temp.clear();
            level++;
        }
        return ans;
    }
};
/* 
Crio Methodology

Milestone 1: Understand the problem clearly
1. Ask questions & clarify the problem statement clearly.
2. Take an example or two to confirm your understanding of the input/output & extend it to test cases
Milestone 2: Finalize approach & execution plan
1. Understand what type of problem you are solving.
     a. Obvious logic, tests ability to convert logic to code
     b. Figuring out logic
     c. Knowledge of specific domain or concepts
     d. Knowledge of specific algorithm
     e. Mapping real world into abstract concepts/data structures
2. Brainstorm multiple ways to solve the problem and pick one
3. Get to a point where you can explain your approach to a 10 year old
4. Take a stab at the high-level logic & write it down.
5. Try to offload processing to functions & keeping your main code small.
Milestone 3: Code by expanding your pseudocode
1. Make sure you name the variables, functions clearly.
2. Avoid constants in your code unless necessary; go for generic functions, you can use examples for your thinking though.
3. Use libraries as much as possible
Milestone 4: Prove to the interviewer that your code works with unit tests
1. Make sure you check boundary conditions
2. Time & storage complexity
3. Suggest optimizations if applicable
*/
Editor is loading...