Program to check whether each node value except leaves is sum of its children value or not in Python

A binary tree has a special property when each internal node's value equals the sum of its children's values. We need to check if this property holds for all non-leaf nodes in the tree.

In this problem, we traverse the tree recursively and verify that each internal node satisfies the sum condition.

Algorithm Steps

The solution uses a depth-first search (DFS) approach ?

  • If the current node is null, return True (empty subtree is valid)
  • If the current node is a leaf (no children), return True
  • For internal nodes, check if node value equals sum of children values
  • Recursively validate left and right subtrees

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.val = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root):
        def dfs(root):
            if root == None:
                return True
            
            # Leaf nodes are always valid
            if root.left == None and root.right == None:
                return True
            
            left = 0
            if root.left:
                left = root.left.val
            
            right = 0
            if root.right:
                right = root.right.val
            
            # Check if current node equals sum of children
            # and recursively validate subtrees
            return (left + right == root.val) and dfs(root.left) and dfs(root.right)
        
        return dfs(root)

# Test the solution
ob = Solution()
root = TreeNode(18)
root.left = TreeNode(8)
root.right = TreeNode(10)
root.left.left = TreeNode(3)
root.left.right = TreeNode(5)

print(ob.solve(root))

The output of the above code is ?

True

How It Works

Let's trace through the example tree ?

  • Root node (18): Children are 8 and 10, sum = 8 + 10 = 18 ?
  • Node (8): Children are 3 and 5, sum = 3 + 5 = 8 ?
  • Node (10): No children (leaf node) ?
  • Nodes (3, 5): Both are leaf nodes ?
18 8 10 3 5 8 + 10 = 18 ? 3 + 5 = 8 ?

Edge Cases

The algorithm handles several edge cases ?

  • Empty tree: Returns True
  • Single node: Leaf node, returns True
  • Nodes with only one child: Missing child contributes 0 to sum

Conclusion

This recursive solution efficiently validates the sum property by checking each internal node against its children's values. The algorithm runs in O(n) time complexity where n is the number of nodes in the tree.

Updated on: 2026-03-25T11:41:27+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements