Root Equals Sum of Children (LeetCode 2236): Solution and Explanation
Given a binary tree of exactly three nodes, return true when the root value equals the sum of its left and right child values.
Intuition
The tree shape is fixed: one root and exactly two children. There is no recursion, no traversal and no missing child to guard against.
Think of a balance scale with the root on one pan and both children on the other. The answer is simply whether the scale balances.
Approach: Direct comparison
- Read the left child's value and the right child's value.
- Add them to get the children's sum.
- Return whether the root value equals that sum.
Step-by-step example
root = [10,4,6]
- The root holds 10.
- The left child holds 4 and the right child holds 6.
- 4 + 6 = 10.
- 10 == 10, so return true.
Code: Python, Java, C++
1class Solution:
2 def checkTree(self, root: Optional[TreeNode]) -> bool:
3 children = root.left.val + root.right.val
4 return root.val == children1class Solution {
2 public boolean checkTree(TreeNode root) {
3 int children = root.left.val + root.right.val;
4 return root.val == children;
5 }
6}1class Solution {
2public:
3 bool checkTree(TreeNode* root) {
4 int children = root->left->val + root->right->val;
5 return root->val == children;
6 }
7};Time and space complexity
O(1)
Exactly three values are read and one addition and one comparison are done.
O(1)
Only one integer is stored for the sum.
Other approaches
General recursive check (time O(n), space O(h))
A recursive function that checks every internal node against its children works for any tree size, which is the follow-up asked by Check Children Sum Property style problems. For this problem it is unnecessary.
Common mistakes
- Adding null checks that hide a wrong assumption. The constraints guarantee both children exist, so a plain sum is correct.
- Forgetting that values can be negative. -5 with children -2 and -3 is a valid true case.
- Comparing the root with only one child, or with the larger child, instead of the sum.
Frequently asked questions
Why is this a tree problem at all?
It is a warm-up for reading node values through left and right pointers. The same pattern appears in larger problems that check a property at every node.
Can the children sum overflow?
No. Each value is between -100 and 100, so the sum is between -200 and 200.