Category: Binary Search Trees

Sum of all nodes with smaller values at a distance K from a given node in a BST

  #include using namespace std;  struct TreeNode {      int data;    TreeNode* left;    TreeNode* right;          TreeNode(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }};  void kDistanceDownSum(TreeNode* root,                      int k, int& sum){          if (root == NULL || k < 0)        return;          if (k == 0) {        sum += root->data;        return;    }              kDistanceDownSum(root->left,                     k – 1, sum);    kDistanceDownSum(root->right,                     k – 1, sum);}  int kDistanceSum(TreeNode* root,                 int target,                 int k, int& sum){        if (root == NULL)        return -1;          if (root->data == target) {        kDistanceDownSum(root->left,                         k – […]

Continue Reading

Sum of nodes in a Binary Search Tree with values from a given range

#include using namespace std;class Node {public:    int val;    Node *left, *right;};Node* newNode(int item){    Node* temp = new Node();    temp->val = item;    temp->left = temp->right = NULL;        return temp;}int sum = 0;int rangeSumBST(Node* root, int low,                int high){        if (root == NULL)        return 0;            queue q;            q.push(root);        while (q.empty() == false) {                        Node* curr = q.front();        q.pop();                        if (curr->val >= low            && curr->val val;        }                        if (curr->left != NULL            && curr->val > low)                        q.push(curr->left);                        if (curr->right != […]

Continue Reading