Difficulty: Easy | Acceptance: 84.90% | Paid: No Topics: Tree, Binary Tree
You are given the root of a binary tree that consists of exactly three 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.
- Examples
- Constraints
- Direct Property Access
- Recursive Approach
Examples
Example 1:
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.
10 is equal to 4 + 6, so we return true.
Example 2:
Input: root = [5,3,1]
Output: false
Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.
Constraints
The tree consists only of the root, its left child, and its right child.
-100 <= Node.val <= 100
Direct Property Access
Intuition Since the problem guarantees the tree consists of exactly three nodes (root, left, right), we can directly access the values of these nodes and perform a simple arithmetic check.
Steps
- Access the value of the root node.
- Access the value of the left child node.
- Access the value of the right child node.
- Return the result of the comparison:
root.val == left.val + right.val.
class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
return root.val == root.left.val + root.right.valComplexity
- Time: O(1)
- Space: O(1)
- Notes: This is the most optimal approach as it performs a constant number of operations.
Recursive Approach
Intuition Although the tree is small, we can treat this as a general tree problem where we check a condition at the current node. This approach demonstrates how one might verify a property for a node in a larger tree structure.
Steps
- Define a helper function or use the main function to accept a node.
- Check if the current node’s value equals the sum of its children’s values.
- Since the tree is guaranteed to have exactly 3 nodes, we only need to perform this check at the root.
class Solution:
def checkTree(self, root: Optional[TreeNode]) -> bool:
# Base case: if node is None (not expected per constraints)
if not root:
return True
# Check the sum condition
return root.val == root.left.val + root.right.valComplexity
- Time: O(1)
- Space: O(1)
- Notes: While functionally similar to the direct approach, recursion adds overhead to the call stack, though here the depth is only 1.