algoadvance

You are given the root of a binary tree containing 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.

Clarifying Questions

  1. Input constraints: Will the given binary tree always have exactly three nodes?
    • Yes, the problem guarantees that.
  2. Node values: Can the node values be negative or zero?
    • Node values can indeed be zero or negative.
  3. Binary tree structure: Since there are exactly three nodes, should we assume that both left and right children are always present?
    • Yes, both left and right children will always be present.

Code

# 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: TreeNode) -> bool:
        return root.val == (root.left.val + root.right.val)

Strategy

  1. TreeNode class:
    • Ensure you have a class TreeNode where we define the basic structure of the nodes of the binary tree.
  2. Checking sum condition:
    • Implement a function checkTree that takes a root node of the binary tree.
    • Since there are exactly three nodes, check if the value of the root node is equal to the sum of the values of its left and right children.
    • Return true if the condition is met, otherwise return false.

Time Complexity

With the problem constraints and guarantees, this solution efficiently checks the condition in constant time and space.

Try our interview co-pilot at AlgoAdvance.com