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
, androot.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 returntrue
orfalse
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:
- Accept the
root
of the binary tree as an argument. The problem statement guarantees that the tree consists of exactly three nodes. - 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.
- Use the equality comparison operator
==
to compare the root's valueroot.val
with the sum of its children's valuesroot.left.val + root.right.val
. - The comparison
root.val == root.left.val + root.right.val
will evaluate to eithertrue
orfalse
. - 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 EvaluatorExample 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:
-
The input provided to the
checkTree
function is theroot
of the binary tree, which in this example has the value10
. The binary tree consists of exactly three nodes, which satisfies the problem requirement. -
Accessing the
root's
value, we haveroot.val
which is10
. -
Similarly, we can access the left child's value
root.left.val
which is4
, and the right child's valueroot.right.val
which is6
. -
We then perform a comparison operation:
root.val == root.left.val + root.right.val
. Substituting the values from our example gives us10 == 4 + 6
. -
The comparison
10 == 10
evaluates totrue
, 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.
Consider the classic dynamic programming of fibonacci numbers, what is the recurrence relation?
Recommended Readings
Everything About Trees A tree is a type of graph data structure composed of nodes and edges Its main properties are It is acyclic doesn't contain any cycles There exists a path from the root to any node Has N 1 edges where N is the number of nodes in the tree and
Binary Tree Min Depth Prereq BFS on Tree problems bfs_intro Given a binary tree find the depth of the shallowest leaf node https algomonster s3 us east 2 amazonaws com binary_tree_min_depth png Explanation We can solve this problem with either DFS or BFS With DFS we traverse the whole tree looking for leaf nodes and record and update the minimum depth as we go With BFS though since we search level by level we are guaranteed to find the shallowest leaf node
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Want a Structured Path to Master System Design Too? Don’t Miss This!