# 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; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up