algoadvance

Leetcode 2236. Root Equals Sum of Children

Problem Statement

Given a binary tree with just one node and its two children, root and exactly two children nodes named left and right. Check if the value of the root node equals the sum of the values of its two children nodes.

Clarifying Questions

Before proceeding with the solution, let’s clarify some points:

  1. Input Constraints: Will the tree always only consist of three nodes - root, left, and right?
  2. Node Values: What kind of values can the nodes have? Are they limited to non-negative integers?
  3. Tree Implementation: How is the tree structured? What is the class definition for the node?

Assuming the tree will always have exactly three nodes, i.e., a root and its two children, and node values are non-negative integers.

Strategy

  1. Tree Node Definition: Define a basic tree node class if not provided.
  2. Sum Check: Implement a function that takes the root of this tree and checks if the value of the root node is equal to the sum of its left and right children nodes.

Code

Here is the Java code that implements the solution to this problem:

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

public class Solution {
    public boolean checkTree(TreeNode root) {
        if (root == null || root.left == null || root.right == null) {
            // If the root is null or it does not have exactly two children, return false.
            return false;
        }
        // Check if the root value is equal to the sum of its left and right children.
        return root.val == root.left.val + root.right.val;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        TreeNode leftChild = new TreeNode(4);
        TreeNode rightChild = new TreeNode(5);
        TreeNode root = new TreeNode(9, leftChild, rightChild);

        System.out.println(solution.checkTree(root)); // Output should be true as 9 = 4 + 5

        TreeNode root2 = new TreeNode(10, leftChild, rightChild);
        System.out.println(solution.checkTree(root2)); // Output should be false as 10 != 4 + 5
    }
}

Time Complexity

The time complexity of this solution is O(1) since it performs a constant number of operations regardless of the input size.

Thus, our approach is optimal and meets the problem’s requirements effectively.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI