Find the range sum of the Binary Search Tree (BST).
Example:
Input: Input: 10/ \ 5 15 / \ \ 3 7 18
low=7, high=15
Output: 32
Approach
Java
public class RangeSumofBST {public static void main(String[] args) {TreeNode root = new TreeNode(10);root.left = new TreeNode(5);root.right = new TreeNode(15);root.left.left = new TreeNode(3);root.left.right = new TreeNode(7);root.right.right = new TreeNode(18);int low = 7, high = 15;int rangeSum = rangeSumBST(root, low, high);System.out.println(rangeSum);}// method to find the range sum of the BSTprivate static int rangeSumBST(TreeNode root, int low, int high) {// if tree is empty return 0if (root == null)return 0;// if root data lies in the given rangeif (root.val <= high && root.val >= low)return root.val + rangeSumBST(root.left, low, high) +rangeSumBST(root.right, low, high);// if root data is less than low then// call for right subtreeelse if (root.val < low)return rangeSumBST(root.right, low, high);// else call for left subtreeelsereturn rangeSumBST(root.left, low, high);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};//function to find the range sum of//the BSTint rangeSumBST(TreeNode* root, int low, int high){//if tree is empty//return 0if(root==NULL)return 0;//if root data lies in the given rangeif(root->data<=high&&root->data>=low)return root->data+rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high);//if root data is less than low then//call for right subtreeelse if(root->data<low)return rangeSumBST(root->right,low,high);//else call for left subtreeelsereturn rangeSumBST(root->left,low,high);}int main(){TreeNode *root=new TreeNode(10);root->left=new TreeNode(5);root->right=new TreeNode(15);root->left->left=new TreeNode(3);root->left->right=new TreeNode(7);root->right->right=new TreeNode(18);int low=7,high=15;cout<<rangeSumBST(root,low,high)<<"\n";return 0;}
No comments:
Post a Comment