0

I am trying to **find and sum ** all numbers in spesific range low - high in BST. I have accessed just the two numbers under the top of the tree. How to access all other numbers. When tried to iterate or traverse, I received errors.

`

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        output = 0
        
        if  root.left.val >= low and root.left.val <= high:
            output += root.left.val
        if  root.right.val >= low and root.right.val <= high:
            output += root.right.val
        return output

`

1
  • In addition to recursion, take advantage of the structure of a BST. For example, every value in the left subtree is less than root.val. If root.val < low, you know that every value in root.left is also less than low, and so there's no need to recurse on the left subtree: you already know the answer will be 0. Commented Dec 8, 2022 at 14:11

2 Answers 2

1

You have to use a recursive function:

def sum_tree(root, low, high):
    value = root.value
    if value < low or value > high:
        value = 0
    if root.left == None and root.right == None:
        return value
    if root.left == None:
        return value + sum_tree(root.right, low, high)
    if root.right == None:
        return value + sum_tree(root.left, low, high)
    return value + sum_tree(root.left, low, high) + sum_tree(root.right, low, high)

Example:

nodes =[5, 6, 6,7, 2, 10, 5, None, 4, 13]
binary_tree = binarytree.build(nodes)

print(binary_tree)
print("Sum min-max:",sum_tree(binary_tree, 5, 10))

Results:

      _____5___
     /         \
  __6___       _6
 /      \     /  \
7       _2   10   5
 \     /
  4   13

Sum min-max: 39
Sign up to request clarification or add additional context in comments.

Comments

0

As @nokla has said, you ideally want a recursive approach to this. Here's a variation on the recursive approach that's quite efficient:

class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        _sum = 0
        def traverse(n):
            nonlocal _sum
            if n:
                if low <= n.val <= high:
                    _sum += n.val
                traverse(n.left)
                traverse(n.right)
        traverse(root)
        return _sum

5 Comments

Thank you very much. So i need a function inside rangeSumBST to make this work? Could you explain to me the steps of your code, so I can understand the logic? What is nonlocal _sum? Is n the tree? I would rate your code 10/10, but I am not allowed :(
Why is traverse(root) outside the function and how does _sum adds its value?
A pity that this function will always visit all nodes. The answer from nokla is better in this respect.
@trincot Unfortunately my pathetic answer was Accepted otherwise I would have deleted it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.