All problems

Problem 267

Range Sum of BST

Easy · 10 pts · Tree, Binary Search Tree, Depth-First Search

Problem

You are given a binary search tree with distinct values and a range [L, R]. Print the sum of all node values v with L <= v <= R. Visiting every node works, but the search tree property lets you skip whole subtrees: if a node's value is below L, its left subtree is entirely below L too, so only search right; if the value is above R, only search left.

Input

First line: integer N, the number of tokens. Second line: N tokens describing the tree in level order, where 'null' marks a missing child. Third line: integers L and R.

Output

Print the sum.

Constraints

1 <= number of nodes <= 20000; values are distinct; 1 <= L <= R <= 100000

Example input

7
10 5 15 3 7 null 18
7 15

Example output

32

Explanation

The tree holds 3, 5, 7, 10, 15 and 18. The values in the range [7, 15] are 7, 10 and 15, and their sum is 32.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Cousins in Binary Tree Next: Node With Maximum Degree