pranay_teja
11/13/2018 - 8:48 AM

LeetCode-RangeOfSumInBST

//
//  Definition for a binary tree node.
//  struct TreeNode {
//      int val;
//      TreeNode *left;
//      TreeNode *right;
//      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
//  };
//
class Solution {
public:
    void traverse(TreeNode* root, int L, int R, int &ans){
        if(root==NULL){
            return;
        }
        if(root->val>=L && root->val<=R){
            ans+=root->val;
            if(root->val==R){
                traverse(root->left,L,R,ans);
            }else{
                traverse(root->left,L,R,ans);
                traverse(root->right,L,R,ans);
            }
        }else if(root->val<L){
            traverse(root->right,L,R,ans);
        }else if(root->val>R){
            traverse(root->left,L,R,ans);
        }
    }
    int rangeSumBST(TreeNode* root, int L, int R) {
        int ans=0;
        traverse(root,L,R,ans);
        return ans;
    }
};