Root Equals Sum of Children

easy trees binary tree simulation

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.

Inputroot = [10,4,6]
Outputtrue
The root is 10 and its children are 4 and 6. Since 4 + 6 = 10, we return true.
Inputroot = [5,3,1]
Outputfalse
The root is 5 but its children sum to 3 + 1 = 4, so we return false.

def 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;
}
Time: O(1) Space: O(1)