LeetCode 2236: Root Equals Sum of Children Solution

Master LeetCode problem 2236 (Root Equals Sum of Children), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2236. Root Equals Sum of Children

Problem Explanation

Explanation

To solve this problem, we can do a simple check at the root node to see if its value is equal to the sum of its left and right children's values. We can recursively traverse the tree to check this condition. If the root is null or the tree does not consist of exactly 3 nodes, we can return false. We can define a recursive function to check this condition and return true if it holds for the current node.

  • Time complexity: O(n) where n is the number of nodes in the tree.
  • Space complexity: O(h) where h is the height of the tree.

Solution Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public boolean rootEqualsSumOfChildren(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) {
            return false;
        }
        return checkSum(root);
    }

    private boolean checkSum(TreeNode node) {
        if (node == null) {
            return true;
        }
        int sumChildren = 0;
        if (node.left != null) {
            sumChildren += node.left.val;
        }
        if (node.right != null) {
            sumChildren += node.right.val;
        }
        return node.val == sumChildren && checkSum(node.left) && checkSum(node.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2236 (Root Equals Sum of Children)?

This page provides optimized solutions for LeetCode problem 2236 (Root Equals Sum of Children) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2236 (Root Equals Sum of Children)?

The time complexity for LeetCode 2236 (Root Equals Sum of Children) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2236 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2236 in Java, C++, or Python.

Back to LeetCode Solutions