#2236

Root Equals Sum of Children

Easy
TreeBinary TreeTreeBinary Tree
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Since we only need to check the values of three nodes, the optimal solution is essentially the same as the brute force approach. However, we can emphasize that this is the best we can do given the constraints.

⚙️

Algorithm

6 steps
  1. 1Step 1: Access the value of the root node.
  2. 2Step 2: Access the value of the left child node.
  3. 3Step 3: Access the value of the right child node.
  4. 4Step 4: Calculate the sum of the left and right child values.
  5. 5Step 5: Compare the root value with the calculated sum.
  6. 6Step 6: Return true if they are equal, otherwise return false.
solution.py8 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7def checkTree(root):
8    return root.val == (root.left.val + root.right.val)

Complexity note: The complexity remains O(1) as we are still performing a constant number of operations.

  • 1The problem is very straightforward due to the fixed size of the tree.
  • 2Understanding how to access child nodes is crucial for tree problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.