-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d15f22f
commit 1deb3f2
Showing
2 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from typing import Optional | ||
|
||
from trees.TreeNode import TreeNode | ||
|
||
|
||
# O(n) time || O(h) space | ||
# n - number of all nodes | ||
# h - height of tree | ||
def range_sum_bst(self, root: Optional[TreeNode], low: int, high: int) -> int: | ||
if not root: | ||
return 0 | ||
|
||
if root.val < low: | ||
return range_sum_bst(self, root.right, low, high) | ||
elif root.val > high: | ||
return range_sum_bst(self, root.left, low, high) | ||
|
||
return root.val + range_sum_bst(self, root.left, low, high) + range_sum_bst(self, root.right, low, high) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import unittest | ||
|
||
from trees.RangeSumOfBST import range_sum_bst | ||
from trees.TreeNode import TreeNode | ||
|
||
|
||
class MyTestCase(unittest.TestCase): | ||
def test_range_sum_bst(self): | ||
root = TreeNode( | ||
val=10, | ||
left=TreeNode( | ||
val=5, | ||
left=TreeNode(val=3), | ||
right=TreeNode(val=7) | ||
), | ||
right=TreeNode( | ||
val=15, | ||
right=TreeNode(18) | ||
) | ||
) | ||
|
||
self.assertEqual(32, range_sum_bst(self, root, 7, 15)) | ||
|
||
def test_range_sum_bst_1(self): | ||
root = TreeNode( | ||
val=10, | ||
left=TreeNode( | ||
val=5, | ||
left=TreeNode(val=3, left=TreeNode(1)), | ||
right=TreeNode(val=7, left=TreeNode(6)) | ||
), | ||
right=TreeNode( | ||
val=15, | ||
left=TreeNode(13), | ||
right=TreeNode(18) | ||
) | ||
) | ||
|
||
self.assertEqual(23, range_sum_bst(self, root, 6, 10)) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |