原题链接在这里:https://leetcode.com/problems/range-sum-of-bst/
题目:
Given the root
node of a binary search tree, return the sum of values of all nodes with value between L
and R
(inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
- The number of nodes in the tree is at most
10000
. - The final answer is guaranteed to be less than
2^31
.
题解:
If current node is null, return 0.
If node value < L, return range sum from its right.
If node value > R, return range sum from its left.
If it is withing [L, R], return range sum from both left and right + node.val.
Time Complexity: O(n).
Space: O(logn).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int rangeSumBST(TreeNode root, int L, int R) { 12 if(root == null){ 13 return 0; 14 } 15 16 if(root.val < L){ 17 return rangeSumBST(root.right, L, R); 18 } 19 20 if(root.val > R){ 21 return rangeSumBST(root.left, L, R); 22 } 23 24 return rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R) + root.val; 25 } 26 }
AC JavaScript:
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 /** 9 * @param {TreeNode} root 10 * @param {number} L 11 * @param {number} R 12 * @return {number} 13 */ 14 var rangeSumBST = function(root, L, R) { 15 if(!root){ 16 return 0; 17 } 18 19 if(root.val < L){ 20 return rangeSumBST(root.right, L, R); 21 } 22 23 if(root.val > R){ 24 return rangeSumBST(root.left, L, R); 25 } 26 27 return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); 28 };
Iteration with stack.
Time Complexity: O(n).
Space: O(logn).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int rangeSumBST(TreeNode root, int L, int R) { 12 if(root == null){ 13 return 0; 14 } 15 16 int sum = 0; 17 Stack<TreeNode> stk = new Stack<>(); 18 stk.push(root); 19 20 while(!stk.isEmpty()){ 21 TreeNode cur = stk.pop(); 22 if(cur == null){ 23 continue; 24 } 25 26 if(cur.val < L){ 27 stk.push(cur.right); 28 }else if(cur.val > R){ 29 stk.push(cur.left); 30 }else{ 31 stk.push(cur.left); 32 stk.push(cur.right); 33 sum += cur.val; 34 } 35 } 36 37 return sum; 38 } 39 }