Root Equals Sum of Children
Problem
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root equals the sum of the values of its two children, or false otherwise.
root = [10,4,6]trueroot = [5,3,1]falsedef check_tree(root):
left = root.left.val
right = root.right.val
total = left + right
return root.val == total
function checkTree(root) {
const left = root.left.val;
const right = root.right.val;
const total = left + right;
return root.val === total;
}
boolean checkTree(TreeNode root) {
int left = root.left.val;
int right = root.right.val;
int total = left + right;
return root.val == total;
}
bool checkTree(TreeNode* root) {
int left = root->left->val;
int right = root->right->val;
int total = left + right;
return root->val == total;
}
Explanation
The tree is guaranteed to be tiny — exactly three nodes: a root with a left child and a right child. There is no recursion or traversal to do; we just read three numbers and check one equation.
First we grab the two child values: left = root.left.val and right = root.right.val. Because the shape of the tree is fixed by the constraints, both children always exist, so we never have to guard against a missing node.
Next we form their sum, total = left + right, and compare it against the root's own value. The answer is simply the boolean root.val == total.
For [10, 4, 6] the children sum to 4 + 6 = 10, which equals the root, so the result is true. For [5, 3, 1] the children sum to 4, which differs from 5, so the result is false.
The whole thing runs in constant time and constant space — there is a fixed amount of work no matter the input.