DDSA Solutions

2236. Root Equals Sum of Children

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

Intuition

Check if root value equals sum of its two children values.

Algorithm

  1. 1If root is null or has no children: return false. Return root.val == root.left.val + root.right.val.

Common Pitfalls

  • Both children must exist. Root with one child: return false.
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?