Prune Tree

amazon, tree related problem

In a binary tree, a complete path is defined as a path from root to a leaf. The
sum of all nodes on that path is defined as the sum of that path. Given a number
K, we have to remove (prune the tree) nodes from the tree which lie on a path
having sum less than K. A node can be part of multiple paths. So we have to
delete it only in case when all paths from it have sum less than K.

***/

#include<iostream>

using namespace std;

#define K 5

struct node {
       int val;
       node *left, *right;
};

bool remove_node(node *n, int left, int right) {
       if (n->left == nullptr && n->right == nullptr)
       {
              return false;
       }
       if(left) {
              n->left = nullptr;
              return true;
       }
       if(right) {
              n->right = nullptr;
              return true;
       }
       return false;
}

int prunetree(node *n, int rank) {
       if(n->left == nullptr && n->right == nullptr) {
              if(rank < K) return 1;
              else return 0;
       }

       int left, right;
       left = prunetree(n->left, rank+n->left->val);
       right = prunetree(n->right, rank+n->right->val);
       if(remove_node(n, left, right)) {
              if(n->left == nullptr && n->right == nullptr) {
                     if(rank < K) return 1;
              }
       }
       return 0;
}


void main() {
       node n[5];
       for (int i = 0; i < 5; i++)
       {
              n[i].left = nullptr;
              n[i].right = nullptr;
       }
       n[0].val = 1;
       n[1].val = 2;
       n[2].val = 4;
       n[3].val = 1;
       n[4].val = 3;
       n[0].left = &n[1];
       n[0].right = &n[2];
       n[1].left = &n[3];
       n[1].right = &n[4];

       prunetree(n, n->val);


}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs