Untitled
class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } public class Solution { public int rangeSumBST(TreeNode root, int low, int high) { return helper(root, low, high); } private int helper(TreeNode node, int low, int high) { if (node == null) return 0; int sum = 0; // If the current node's value is within the range, add it to sum if (node.val >= low && node.val <= high) { sum += node.val; } // If node's value is greater than low, recurse on the left child if (node.val < low) { sum += helper(node.right, low, high); } // If node's value is less than high, recurse on the right child if (node.val > high) { sum += helper(node.left, low, high); } return sum; } }
Leave a Comment