Root Equals Sum of Children — LeetCode 2236 Python Solution

EasyTreeBinary Tree
Problem
#2236
Reading time
2 min

The problem

You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.

Example

Input
root = [10,4,6]
Output
true
Explanation
The values of the root, its left child, and its right child are 10, 4, and 6, respectively.

Python solution

Python
# Definition for a binary tree 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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(h) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2236. Root Equals Sum of Children is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Tree and Binary Tree.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2236. Root Equals Sum of Children?
LeetCode 2236. Root Equals Sum of Children is rated Easy on LeetCode.
What is the time complexity of LeetCode 2236. Root Equals Sum of Children?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2236. Root Equals Sum of Children?
The Python solution on this page uses O(h) auxiliary space.
What topics does LeetCode 2236. Root Equals Sum of Children cover?
LeetCode 2236. Root Equals Sum of Children is tagged Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview