---
# System prepended metadata

title: 0938. Range Sum of BST
tags: [Leetcode, BFS, FaceBook, DFS, Easy]

---

# 0938. Range Sum of BST
###### tags: `Leetcode` `Easy` `BFS` `DFS` `FaceBook`
Link: https://leetcode.com/problems/range-sum-of-bst/submissions/
## Code
### BFS
```java=
class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        int sum = 0;
        if(root == null) return 0;
        Queue<TreeNode> q  = new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()){
            TreeNode node = q.poll();
            if(node == null)continue;
            if(node.val>=low && node.val<=high){
                sum+=node.val;
                q.add(node.right);
                q.add(node.left);
            }
            else if(node.val<low){
                q.add(node.right);
            }
            else if(node.val>high){
                q.add(node.left);
            }
        }
        return sum;
    }
}
```
### DFS
```java=
class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        int sum = 0;
        if(root == null) return sum;
        if(root.val>=low&&root.val<=high){
            sum+=root.val;
            sum+=rangeSumBST(root.left, low, high);
            sum+=rangeSumBST(root.right, low, high);
        }
        else if(root.val<low){
            sum+=rangeSumBST(root.right, low, high);
        }
        else if(root.val>high){
            sum+=rangeSumBST(root.left, low, high);
        }
        return sum;
    }
}
```