Root Equals Sum of Children - Problem

You're working with a perfect small binary tree that has exactly 3 nodes: one root node and two children (left and right). Your task is simple but fundamental to tree algorithms!

Given the root of this 3-node binary tree, determine if the root's value equals the sum of its two children's values.

Goal: Return true if root.val == left.val + right.val, otherwise return false.

Example: If the tree looks like [10, 4, 6], then 10 == 4 + 6, so return true.

Input & Output

example_1.py โ€” Balanced Tree
$ Input: [10, 4, 6]
โ€บ Output: true
๐Ÿ’ก Note: The root value 10 equals the sum of children: 4 + 6 = 10, so return true
example_2.py โ€” Unbalanced Tree
$ Input: [5, 3, 1]
โ€บ Output: false
๐Ÿ’ก Note: The root value 5 does not equal the sum of children: 3 + 1 = 4 โ‰  5, so return false
example_3.py โ€” Zero Sum Case
$ Input: [1, 1, 0]
โ€บ Output: true
๐Ÿ’ก Note: The root value 1 equals the sum of children: 1 + 0 = 1, so return true

Constraints

  • The tree consists of exactly 3 nodes: 1 root + 2 children
  • Node values are in range [-100, 100]
  • Both left and right children are guaranteed to exist

Visualization

Tap to expand
Root Equals Sum of Children Problem1046Step 1: root.val = 10Step 2: left.val = 4, right.val = 6Step 3: sum = 4 + 6 = 10Step 4: 10 == 10 โœ“ Return trueAlgorithm: return root.val == root.left.val + root.right.valTime: O(1) | Space: O(1)
Understanding the Visualization
1
Read Root Value
Access the parent node's value
2
Read Children Values
Access both left and right child values
3
Calculate Sum
Add the two children values together
4
Compare
Check if root equals the sum
Key Takeaway
๐ŸŽฏ Key Insight: With exactly 3 nodes, this becomes a simple arithmetic comparison rather than a complex tree algorithm!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
52.0K Views
High Frequency
~5 min Avg. Time
2.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen