← 返回 meta 的题目列表Average of Elements in BST within Range
类型:online_judge
Given a binary search tree and a closed interval [low, high], calculate the average of all node values within this range.
The tree node is defined as follows:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Implement a function average_of_elements(root: TreeNode, low: int, high: int) -> float that returns the average of values of nodes within the specified range.
Example Inputs and Outputs:
# Tree structure
# 6
# / \
# 4 8
# / \ / \
#3 2 7 9
# /
#2
average_of_elements(root, 3, 10) # Returns 6.0
average_of_elements(root, 2, 5) # Returns 3.5
Example
Input
root, 3, 10