Difficulty: 🟢 Easy
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 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.
- The tree consists only of the root, its left child, and its right child.
100 <= Node.val <= 100
Python3
# 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
The given solution provides a recursive approach to check if the value of the root node is equal to the sum of the values of its two children.
Here is a step-by-step overview of the solution:
- Check if the root node is None. If it is, return False as there is no node to check.
- Check if the value of the root node is equal to the sum of the values of its left and right children.
- Recursively call the
checkTree
function for the left child of the root. - Recursively call the
checkTree
function for the right child of the root. - Return the result of the logical AND operation between step 2 and the results from steps 3 and 4.
The time complexity for this solution is O(1) because we are only dealing with a fixed number of nodes (3 nodes) in the binary tree.
The space complexity is O(1) because we are not using any additional space that grows with the input.
The given solution provides a simple approach to check if the value of the root node in a binary tree is equal to the sum of the values of its two children. It recursively traverses the tree and performs the required checks. The solution has a time complexity of O(1) and a space complexity of O(1).
NB: If you want to get community points please suggest solutions in other languages as merge requests.