oneby7

Binary Trees Depth first: return a value up

362. Children Sum Property

Medium

You are given root, the root node of a binary tree. Return true if the tree has the children sum property, and false otherwise.

A tree has the property when every node with at least one child holds a value equal to the sum of its children's values. A missing child counts as 0, so a node with a single child must equal that child. A leaf has no children and always passes. An empty tree has the property.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

142311066

Input: root = [10, 4, 6, 1, 3, null, 6, null, null, 2, 1]

Output: true

Explanation: 10 = 4 + 6, 4 = 1 + 3 and 3 = 2 + 1. Node 6 has only a right child, 6, and its missing left child counts as 0. The leaves 1, 6, 2 and 1 have nothing to check.

Example 2

-5-500253

Input: root = [0, -5, 5, -5, 0, 2, 3]

Output: true

Explanation: 0 = −5 + 5, −5 = −5 + 0 and 5 = 2 + 3. Values can be negative or zero.

Example 3

371421255

Input: root = [12, 7, 5, 3, 4, 5, null, null, null, 1, 2]

Output: false

Explanation: The root, 7 and 5 all pass. But node 4 has children 1 and 2, which add up to 3.

Check your understanding

Work out the answer for this input before you write any code.

root = [5, 5, null, 5]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.