DDSA Solutions

2236. Root Equals Sum of Children

Time: O(1)
Space: O(1)

Problem Overview

Binary tree root equals sum of children only when both children exist and root.val == left.val + right.val.

Advertisement

Intuition

Binary tree root equals sum of children only when both children exist and root.val == left.val + right.val. Missing child or null root means false.

Algorithm

  1. 1If root is null, return false.
  2. 2If left or right child is null, return false.
  3. 3Return root.val == root.left.val + root.right.val.

Example Walkthrough

Input: root = [10,4,-6]

  1. 1.Both children exist: 10 == 4 + (-6)? 10 == -2 — false.

Output: false

Common Pitfalls

  • Leaf node (no children) → false, not vacuously true.
  • Only exactly two children qualify.
  • Values can be negative — sum still valid.
2236.cs
C#
// Approach: Check root.val == left.val + right.val directly.
// Time: O(1) Space: O(1)

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


public class Solution
{
    public bool CheckTree(TreeNode root)
    {
        return root.val == (root.left.val + root.right.val);
    }
}
Advertisement
Was this solution helpful?

Related Problems