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 is equal to thesum of the values of its two children, or _false otherwise.

Examples

Example 1

1
2
3
4
5
6
7

![](https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png)

Input: root = [10,4,6]
Output: true
Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.
10 is equal to 4 + 6, so we return true.

Example 2

1
2
3
4
5
6
7

![](https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png)

Input: root = [5,3,1]
Output: false
Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.

Constraints

  • The tree consists only of the root, its left child, and its right child.
  • -100 <= Node.val <= 100

Solution

Method 1 - Direct Comparison

Intuition

The problem is very simple: since the tree only has three nodes (root, left, right), we just need to check if the root’s value equals the sum of its two children. No recursion or traversal is needed.

Approach

Access the root, its left, and right children. Return true if root.val == root.left.val + root.right.val, otherwise return false. This is a direct comparison.

Code

1
2
3
4
5
6
class Solution {
public:
    bool checkTree(TreeNode* root) {
        return root->val == root->left->val + root->right->val;
    }
};
1
2
3
func checkTree(root *TreeNode) bool {
    return root.Val == root.Left.Val+root.Right.Val
}
1
2
3
4
5
class Solution {
    public boolean checkTree(TreeNode root) {
        return root.val == root.left.val + root.right.val;
    }
}
1
2
3
4
5
class Solution {
    fun checkTree(root: TreeNode?): Boolean {
        return root!!.value == root.left!!.value + root.right!!.value
    }
}
1
2
3
class Solution:
    def checkTree(self, root: Optional[TreeNode]) -> bool:
        return root.val == root.left.val + root.right.val
1
2
3
4
5
6
7
impl Solution {
    pub fn check_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
        let node = root.unwrap();
        let n = node.borrow();
        n.val == n.left.as_ref().unwrap().borrow().val + n.right.as_ref().unwrap().borrow().val
    }
}
1
2
3
4
function checkTree(root: TreeNode | null): boolean {
    if (!root || !root.left || !root.right) return false;
    return root.val === root.left.val + root.right.val;
}

Complexity

  • ⏰ Time complexity: O(1) — Only a single comparison is made.
  • 🧺 Space complexity: O(1) — No extra space is used.