Loading

LeetCode problem#938

Range Sum of BST

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

34 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 *     int val;
5 *     TreeNode left;
6 *     TreeNode right;
7 *     TreeNode() {}
8 *     TreeNode(int val) { this.val = val; }
9 *     TreeNode(int val, TreeNode left, TreeNode right) {
10 *         this.val = val;
11 *         this.left = left;
12 *         this.right = right;
13 *     }
14 * }
15 */
16class Solution {
17    public int rangeSumBST(TreeNode root, int low, int high) {
18        if (root == null) {
19            return 0;
20        }
21
22        int sum = 0;
23        if (root.val >= low && root.val <= high) {
24            sum += root.val;
25        }
26        if (root.val > low) {
27            sum += rangeSumBST(root.left, low, high);
28        }
29        if (root.val < high) {
30            sum += rangeSumBST(root.right, low, high);
31        }
32        return sum;
33    }
34}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.