LeetCode Entry

938. Range Sum of BST

7.12.2022 easy 2022 kotlin

fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int =

938. Range Sum of BST easy

https://t.me/leetcode_daily_unstoppable/44


    fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int =
	if (root == null) 0 else
		with(root) {
			(if (`val` in low..high) `val` else 0) +
				(if (`val` < low) 0 else rangeSumBST(left, low, high)) +
				(if (`val` > high) 0 else rangeSumBST(right, low, high))
		}

  • be careful with ternary operations, better wrap them in a brackets

Space: O(log N), Time: O(R), r - is a range [low, high]