Root Equals Sum of Children — LeetCode 2236 Python Solution
- Problem
- #2236
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
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
# 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.valComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.