• + 0 comments

    C++

    class Node {
        public:
            int data;
            Node* left;
            Node* right;
            Node(int x) : data(x), left(nullptr), right(nullptr) {}
    };
    
    void inorder(Node* root, vector<int>& res_value) {
        if(!root) return;
        inorder(root->left, res_value);
        res_value.push_back(root->data);
        inorder(root->right, res_value);
    }
    
    void swapNodesUtil(Node* root, int level, int k) {
        if(!root || (!root->left && !root->right)) return;
    
        
        if(level % k == 0) {
            swap(root->left, root->right);
        }
        swapNodesUtil(root->left, level + 1, k);
        swapNodesUtil(root->right, level + 1, k);
        
    }
    
    vector<vector<int>> swapNodes(vector<vector<int>> indexes, vector<int> queries) {
        Node* root = new Node(1);
        
        //build tree from queue
        queue<Node*> q;
        q.push(root);
        for(int i = 0;i<indexes.size();i++) {
            Node* cur = q.front();
            q.pop();
            cout << cur->data << endl;
            if(indexes[i][0] != -1)
            {
                cur->left = new Node(indexes[i][0]);
                q.push(cur->left);
            }
    
            if(indexes[i][1] != -1) {
                cur->right = new Node(indexes[i][1]);
                q.push(cur->right);
            }
            
        }
        
        // swap node and travelsal to save tree to array
        vector<vector<int>> res;
        for(int i = 0;i<queries.size();i++) {
            vector<int> res_value;
            swapNodesUtil(root, 1, queries[i]);
            inorder(root,res_value);
            res.push_back(res_value);
        }
        return res;
        
    }