📓
Algorithms
  • Introduction to Data Structures & Algorithms with Leetcode
  • Strings
    • Dutch Flags Problem
      • List Partitoning
    • Counters
      • Majority Vote
      • Removing Parentheses
      • Remove Duplicates from Sorted Array
    • Maths
      • Lone Integer
      • Pigeonhole
      • Check If N and Its Double Exist
      • Find Numbers with Even Number of Digits
    • Two Pointers
      • Remove Element
      • Replace Elements with Greatest Element on Right Side
      • Valid Mountain Array
      • Sort Array by Parity
      • Squares of a Sorted Array
      • Max Consecutive Ones
    • Sliding Window
      • Max Consecutive Ones 3
    • Stacks
      • Balanced Brackets
    • General Strings & Arrays
      • Move Zeros
      • Unique Elements
      • Merge Sorted Array
    • Matrices
      • Valid Square
      • Matrix Search Sequel
  • Trees
    • Untitled
  • Recursion
    • Introduction
    • Backtracking
      • Permutations
  • Dynamic Programming
    • Introduction
    • Minimum (Maximum) Path to Reach a Target
      • Min Cost Climbing Stairs
      • Coin Change
      • Minimum Path Sum
      • Triangle
      • Minimum Cost to Move Chips to The Same Position
      • Consecutive Characters
      • Perfect Squares
    • Distinct Ways
      • Climbing Stairs
      • Unique Paths
      • Number of Dice Rolls with Target Sum
    • Merging Intervals
      • Minimum Cost Tree From Leaf Values
    • DP on Strings
      • Levenshtein Distance
      • Longest Common Subsequence
  • Binary Search
    • Introduction
      • First Bad Version
      • Sqrt(x)
      • Search Insert Position
    • Advanced
      • KoKo Eating Banana
      • Capacity to Ship Packages within D Days
      • Minimum Number of Days to Make m Bouquets
      • Split array largest sum
      • Minimum Number of Days to Make m Bouquets
      • Koko Eating Bananas
      • Find K-th Smallest Pair Distance
      • Ugly Number 3
      • Find the Smallest Divisor Given a Threshold
      • Kth smallest number in multiplication table
  • Graphs
    • Binary Trees
      • Merging Binary Trees
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Populating Next Right Pointers in Each Node
      • Populating Next Right Pointers in Each Node II
      • 106. Construct Binary Tree from Inorder and Postorder Traversal
      • Serialise and Deserialise a Linked List
      • Maximum Depth of Binary Tree
      • Lowest Common Ancestor of a Binary Tree
    • n-ary Trees
      • Untitled
      • Minimum Height Trees
    • Binary Search Trees
      • Counting Maximal Value Roots in Binary Tree
      • Count BST nodes in a range
      • Invert a Binary Tree
      • Maximum Difference Between Node and Ancestor
      • Binary Tree Tilt
  • Practice
  • Linked Lists
    • What is a Linked List?
    • Add Two Numbers
      • Add Two Numbers 2
    • Reverse a Linked List
    • Tortoise & Hare Algorithm
      • Middle of the Linked List
  • Bitshifting
    • Introduction
  • Not Done Yet
    • Uncompleted
    • Minimum Cost For Tickets
    • Minimum Falling Path Sum
Powered by GitBook
On this page

Was this helpful?

  1. Graphs
  2. Binary Search Trees

Count BST nodes in a range

PreviousCounting Maximal Value Roots in Binary TreeNextInvert a Binary Tree

Last updated 4 years ago

Was this helpful?

Given a binary search tree root, and integers lo and hi, return the count of all nodes in root whose values are between lo and hi (inclusive).

For example, with this tree and lo = 5 and hi = 10, return 3 since only 7, 8, 9 are between [5, 10].

   3
  / \
 2   9
    / \
   7   12
  / \
 4   8

Example 1

Input

root = [3, null, [5, null, null]]
lo = 4
hi = 7

Output

1

Our base case is if the node value is 0, we want to return nothing.

Binary Search Trees have 2 properties that interest us:

  • The left node is smaller than the parent

  • The right node is larger than or equal to the parent

Therefore if our hi is less than the value, we go to the left. This is because:

lo = 5, hi = 10.

If our hi is less than our value, we want to go to the left. This is because all numbers in the right nodes path will always be larger than hi due to the nature of binary search trees.

If our lo is higher than our value, we want to go to the right. Again, this is because all values in the left hand side are less than our lowest value and due to the nature of binary search trees we want to go to the right.

Eventually, we only go down the paths that have nodes that can possibly be within the appropriate range.

Left is always smaller than current value, right is always equal to or higher than current value.

Otherwise, the current value is within the range and we we add together our 2 recursive calls along with adding + 1 to the counter.

# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def solve(self, root, lo, hi):
        if not root:
            return 0
        if hi < root.val:
            return self.solve(root.left, lo, hi)
        elif lo > root.val:
            return self.solve(root.right, lo, hi)
        else:
            return self.solve(root.left, lo, hi) + self.solve(root.right, lo, hi) + 1
https://binarysearch.com/problems/Count-BST-nodes-in-a-range