题目地址:https://leetcode.com/contest/weekly-contest-110/problems/range-sum-of-bst/ 题目描述 Given therootnode of a binary search tree, return the sum of values of all nodes with value betweenLandR(inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: ...
然后我们来看答案,简单的递归: class Solution { public int rangeSumBST(TreeNode root, int L, int R) { if (root == null) { return 0; } int sum = 0; if (root.val > L) { sum += rangeSumBST(root.left, L, R); } if (root.val < R) { sum += rangeSumBST(root.right, L,...
x):# self.val = x# self.left = None# self.right = NoneclassSolution(object):defrangeSumBST(self,root,L,R):defdfs(node):ifnode:ifL<=node.val<=R:self.ans+=node.valifL<node.val:dfs(node.left)ifnode.val<R:dfs(node.right)self.ans=0dfs(root)returnself.ans ...
return root->val + rangeSumBST(root->left,L,R) + rangeSumBST(root->right,L,R); } }; Github 同步地址: https://github.com/grandyang/leetcode/issues/938 参考资料: https://leetcode.com/problems/range-sum-of-bst/ https://leetcode.com/problems/range-sum-of-bst/discuss/205181/Java-4-...
class Solution { int sum = 0; public int rangeSumBST(TreeNode root, int L, int R) { if (root == null) { return 0; } if (root.val >= L && root.val <= R) { sum += root.val; rangeSumBST(root.left, L, R); rangeSumBST(root.right, L, R); ...
1 class Solution 2 { 3 public: 4 int rangeSumBST(TreeNode* root, int L, int R) 5 { 6 int result = 0; 7 if(root->left) 8 result += r...
classSolution{ public: int rangeSumBST(TreeNode*root,intL,intR) { if (root==NULL) return 0; if (root->val<L) { return rangeSumBST(root->right,L,R); } else if (root->val>R) { return rangeSumBST(root->left,L,R); }
[leetcode] 938. Range Sum of BST Description 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.
今天介绍的是LeetCode算法题中Easy级别的第221题(顺位题号是938)。给定二叉搜索树的根节点,返回节点值在[L,R]之间的所有节点的值的总和。二叉搜索树的节点值唯一。例如: 输入:root = [10,5,15,3,7,null,18],L = 7,R = 15 输出:32 输入:root = [10,5,15,3,7,13,18,1,null,6],L = 6,R...
LeetCode 938 - Range Sum of BST (Easy) Given therootnode of a binary search tree, returnthe sum of values of all nodes with a value in the range[low, high]. Example 1: Input: root = [10,5,15,3,7,null,18], low = 7, high = 15...