All problems

Problem 151

Path Sum

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

Problem

You are given a binary tree and a target S. Decide whether the tree has a root-to-leaf path whose node values add up to exactly S. The path must start at the root and end at a leaf, which is a node with no children; stopping halfway does not count. Recursively subtract each node's value from the target as you go down. At a leaf, check whether the remaining target equals the leaf's value.

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 (the same format LeetCode uses). Third line: the target S.

Output

Print YES or NO.

Constraints

1 <= number of nodes <= 5000; -1000 <= value <= 1000; -1000000 <= S <= 1000000

Example input

13
5 4 8 11 null 13 4 7 2 null null null 1
22

Example output

YES

Explanation

The path 5 → 4 → 11 → 2 goes from the root to the leaf 2, and 5 + 4 + 11 + 2 = 22, which is the target. So the answer is YES.

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

Previous: Balanced Binary Tree Next: Validate Binary Search Tree