Search code examples
pythonsearchbinary-search-tree

Iterate/traverse BST Python


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

`


Solution

  • 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