- Binary Search Tree, Binary Search Trees, DFS, Mathematical, Recursion, Tree

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 – 1, sum);        return 0;    }          int dl = -1;              if (target < root->data) {        dl = kDistanceSum(root->left,                          target, k, sum);    }              if (dl != -1) {                          if (dl + 1 == k)            sum += root->data;                          return -1;    }              int dr = -1;    if (target > root->data) {        dr = kDistanceSum(root->right,                          target, k, sum);    }      if (dr != -1) {                  if (dr + 1 == k)            sum += root->data;                                  else            kDistanceDownSum(root->left,                             k – dr – 2, sum);          return 1 + dr;    }              return -1;}  TreeNode* insertNode(int data,                     TreeNode* root){        if (root == NULL) {        TreeNode* node = new TreeNode(data);        return node;    }          else if (data > root->data) {        root->right = insertNode(            data, root->right);    }          else if (data data) {        root->left = insertNode(            data, root->left);    }          return root;}  void findSum(TreeNode* root, int target,             int K){              int sum = 0;      kDistanceSum(root, target, K, sum);          cout