|
| 1 | +package by.andd3dfx.tree; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | + |
| 6 | +/** |
| 7 | + * <pre> |
| 8 | + * <a href="https://leetcode.com/problems/range-sum-of-bst/description/">Task description</a> |
| 9 | + * |
| 10 | + * Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value |
| 11 | + * in the inclusive range [low, high]. |
| 12 | + * |
| 13 | + * Example 1: |
| 14 | + * <img src="https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg"/> |
| 15 | + * Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 |
| 16 | + * Output: 32 |
| 17 | + * Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32. |
| 18 | + * |
| 19 | + * Example 2: |
| 20 | + * <img src="https://assets.leetcode.com/uploads/2020/11/05/bst2.jpg"/> |
| 21 | + * Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 |
| 22 | + * Output: 23 |
| 23 | + * Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23. |
| 24 | + * </pre> |
| 25 | + */ |
| 26 | +public class RangeSumOfBST { |
| 27 | + |
| 28 | + public static int rangeSumBST(TreeNode root, int low, int high) { |
| 29 | + Deque<TreeNode> queue = new ArrayDeque<>(); |
| 30 | + queue.add(root); |
| 31 | + var sum = 0; |
| 32 | + while (!queue.isEmpty()) { |
| 33 | + var element = queue.pop(); |
| 34 | + if (element.left != null) { |
| 35 | + queue.add(element.left); |
| 36 | + } |
| 37 | + if (element.right != null) { |
| 38 | + queue.add(element.right); |
| 39 | + } |
| 40 | + if (low <= element.val && element.val <= high) { |
| 41 | + sum += element.val; |
| 42 | + } |
| 43 | + } |
| 44 | + return sum; |
| 45 | + } |
| 46 | + |
| 47 | + public static class TreeNode { |
| 48 | + |
| 49 | + int val; |
| 50 | + TreeNode left; |
| 51 | + TreeNode right; |
| 52 | + |
| 53 | + TreeNode(int val) { |
| 54 | + this.val = val; |
| 55 | + } |
| 56 | + |
| 57 | + TreeNode(int val, TreeNode left, TreeNode right) { |
| 58 | + this.val = val; |
| 59 | + this.left = left; |
| 60 | + this.right = right; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments