2236. Root Equals Sum of Children


Problem Description

In this problem, we're working with a very small binary tree, one that only has three nodes: a root node, a left child, and a right child. We're asked to determine if the value of the root node is equal to the sum of the values of its two children. If this condition is true, we should return true; otherwise, we return false. It's a straightforward problem focused on understanding the basic properties of a binary tree and how to access the values of its nodes.

Intuition

Given that the tree has exactly three nodes, this problem is greatly simplified compared to most tree problems. There's no need for complex traversal or recursion. The intuition behind the solution is based on the direct relationship between the nodes. By definition, the sum of the children's values can be compared directly with the root's value.

We can arrive at this solution approach by considering the following:

  • Since the tree structure is guaranteed, we know that the root, the left child, and the right child all exist.
  • We can access the values of these three nodes directly using root.val, root.left.val, and root.right.val.
  • The sum of the values of the left and right children can be obtained with a simple addition: root.left.val + root.right.val.
  • By comparing this sum to root.val, we can determine whether they are equal and thus return true or false accordingly.

This solution leverages the fact that, in Python, comparisons return a boolean value, which aligns perfectly with the requirement of our function to return a boolean.

Learn more about Tree and Binary Tree patterns.

Solution Approach

The implementation of the solution is straightforward given the simplicity of the problem. Here's a step-by-step walkthrough of the algorithm used in the provided solution code:

  1. Accept the root of the binary tree as an argument. The problem statement guarantees that the tree consists of exactly three nodes.
  2. Since the tree structure is known and fixed, we have direct access to the root's value as well as its left and right children's values.
  3. Use the equality comparison operator == to compare the root's value root.val with the sum of its children's values root.left.val + root.right.val.
  4. The comparison root.val == root.left.val + root.right.val will evaluate to either true or false.
  5. Since the desired output of checkTree function is a boolean, directly return the result of that comparison.

There are no complex data structures, patterns, or algorithms needed to solve this problem. The simplicity of the binary tree's structure allows us to perform a direct comparison without the need for additional code or complex logic.

The code snippet follows this logic concisely:

# Definition for a binary [tree](/problems/tree_intro) node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def checkTree(self, root: Optional[TreeNode]) -> bool:
        return root.val == root.left.val + root.right.val

In this code, the comparison root.val == root.left.val + root.right.val is the core of the solution. This comparison uses fundamental arithmetic (addition) and a basic equality check. It exploits the fact that in Python, a comparison operation itself yields a boolean result. This concise code results in an elegant and efficient implementation of the required functionality.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's consider a simple example to illustrate the solution approach. Imagine we have a binary tree as follows:

    10
   /  \
  4    6

Here's the step-by-step walkthrough, with this specific tree in mind:

  1. The input provided to the checkTree function is the root of the binary tree, which in this example has the value 10. The binary tree consists of exactly three nodes, which satisfies the problem requirement.

  2. Accessing the root's value, we have root.val which is 10.

  3. Similarly, we can access the left child's value root.left.val which is 4, and the right child's value root.right.val which is 6.

  4. We then perform a comparison operation: root.val == root.left.val + root.right.val. Substituting the values from our example gives us 10 == 4 + 6.

  5. The comparison 10 == 10 evaluates to true, which is the result we expect, given that the sum of the children's values equals the root's value.

In this example, the checkTree function would therefore return true, correctly indicating that the value of the root is equal to the sum of its children's values. This demonstrates the effectiveness of directly comparing the values to solve this problem without the need for traversing the tree or implementing complex logic.

Solution Implementation

1# Definition for a binary tree node.
2class TreeNode:
3    """
4    A class to represent a node in a binary tree.
5  
6    Attributes:
7    val (int): The value of the node.
8    left (TreeNode): A reference to the left subtree.
9    right (TreeNode): A reference to the right subtree.
10    """
11    def __init__(self, val=0, left=None, right=None):
12        """
13        Initializes a TreeNode with a value and optional left and right subtrees.
14      
15        Parameters:
16        val (int): The value to store in the node. Default is 0.
17        left (TreeNode): The left subtree. Default is None.
18        right (TreeNode): The right subtree. Default is None.
19        """
20        self.val = val
21        self.left = left
22        self.right = right
23
24class Solution:
25    def check_tree(self, root: TreeNode) -> bool:
26        """
27        Checks if the value of the root node is equal to the sum of the values 
28        of its left and right child nodes.
29      
30        Parameters:
31        root (TreeNode): The root node of the binary tree.
32      
33        Returns:
34        bool: True if the root node's value is equal to the sum of its children's values,
35              False otherwise.
36        """
37        # Check if root exists to prevent AttributeError on accessing None.
38        if root is None:
39            return False
40
41        # Calculate the sum of the values of the left and right child nodes.
42        children_sum = (root.left.val if root.left else 0) + (root.right.val if root.right else 0)
43      
44        # Return whether the root's value is equal to the sum of its children's values.
45        return root.val == children_sum
46
1/**
2 * Definition for a binary tree node.
3 */
4class TreeNode {
5    int val; // Value of the node
6    TreeNode left; // Reference to the left child node
7    TreeNode right; // Reference to the right child node
8
9    // Constructor for tree node with no children
10    TreeNode() {}
11
12    // Constructor for tree node with a specified value
13    TreeNode(int val) { this.val = val; }
14
15    // Constructor for tree node with specified value and children
16    TreeNode(int val, TreeNode left, TreeNode right) {
17        this.val = val;
18        this.left = left;
19        this.right = right;
20    }
21}
22
23class Solution {
24  
25    /**
26     * Checks if the value of the root is equal to the sum of its left and right child nodes.
27     * 
28     * @param root The root of the binary tree.
29     * @return true if the root's value is the sum of its children's values, false otherwise.
30     */
31    public boolean checkTree(TreeNode root) {
32        // Check if the value of the root node is the sum of values of the left and right child nodes.
33        // It assumes root, root.left, and root.right are not null.
34        return root.val == root.left.val + root.right.val;
35    }
36}
37
1// Definition for a binary tree node.
2struct TreeNode {
3    int val;             // The value of the node
4    TreeNode *left;      // Pointer to the left child
5    TreeNode *right;     // Pointer to the right child
6  
7    // Constructor to initialize node with default value 0 and null children
8    TreeNode() : val(0), left(nullptr), right(nullptr) {}
9  
10    // Constructor to initialize node with a given integer value and null children
11    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12  
13    // Constructor to initialize node with a given value and left and right children
14    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
15};
16
17class Solution {
18public:
19    // This method checks if the root node's value is equal to the sum of its left and right children's values.
20    bool checkTree(TreeNode* root) {
21        // Ensure that the left and right children are not nullptr before accessing their values
22        if (root == nullptr || root->left == nullptr || root->right == nullptr) {
23            // If one of the nodes is nullptr, we cannot perform the check, so we return false
24            return false;
25        }
26      
27        // Perform the check by comparing the root's value with the sum of its children's values
28        return root->val == root->left->val + root->right->val;
29    }
30};
31
1// This function checks if the value of the root node of a binary tree is equal to the sum of the values of its left and right child nodes.
2
3// A TypeScript interface for the binary tree node structure.
4interface TreeNode {
5    val: number;
6    left: TreeNode | null;
7    right: TreeNode | null;
8}
9
10function checkTree(root: TreeNode | null): boolean {
11    // Check if the root node is not null.
12    if (root) {
13        // Return true if the value of the root node equals the sum of the values
14        // of its left and right child nodes. Otherwise, return false.
15        return root.val === (root.left ? root.left.val : 0) + (root.right ? root.right.val : 0);
16    }
17    // If the root is null, the binary tree does not exist, hence return false.
18    return false;
19}
20

Time and Space Complexity

The given Python function checkTree checks if the sum of the values of the left and right children of the root of a binary tree is equal to the value of the root itself.

Time Complexity

The time complexity of the function is O(1). This is because the function performs a constant number of operations: it accesses the value of the root node and the values of its immediate left and right children, and then it performs an addition and a comparison. Since these operations are constant and do not depend on the size of the input (i.e., the number of nodes in the tree), the time complexity is constant.

Space Complexity

The space complexity of the function is also O(1). The function uses a fixed amount of space: it stores two integer values (the sum of the left and right child values and the value of the root) and returns a boolean. Since the space used does not depend on the size of the input and no additional space is allocated during the execution of the function (e.g., no recursive calls or new data structures are created), the space complexity is constant.

Learn more about how to find time and space complexity quickly using problem constraints.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

You are given an array of intervals where intervals[i] = [start_i, end_i] represent the start and end of the ith interval. You need to merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More