Open In App

Check for Children Sum Property in a Binary Tree

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree, the task is to check for every node, its value is equal to the sum of values of its immediate left and right child. For NULL values, consider the value to be 0. Also, leaves are considered to follow the property.

Example:

Input:

Check-for-Children-Sum-Property-in-a-Binary-Tree_2

Output: 1
Explanation: The above binary tree follows the Children Sum Property.

Input:

Check-for-Children-Sum-Property-in-a-Binary-Tree_1

Output: 0
Explanation: The above binary tree doesn’t follows the Children Sum Property as 5 + 2 != 8

[Expected Approach] Using Recursion – O(n) Time and O(h) Space:

The idea is traverse the binary tree recursively and check if the root node and its children satisfy the children sum property, which states that a node’s value should equal the sum of its left and right children’s values. The function checks if the current node’s value matches this sum and recursively checks for both the subtrees.

Below is the implementation of this approach:

C++
// C++ Program to check children sum property
#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node* left;
        Node* right;
        Node (int x) {
            data = x;
            left = nullptr;
            right = nullptr;
        }
};

// returns 1 if children sum property holds
// for the given node and both of its children
int isSumProperty(Node* root) {

    // If root is NULL or it's a leaf node
    // then return true
    if (root == nullptr
        || (root->left == nullptr && root->right == nullptr))
        return 1;
        
    int sum = 0;
    
    // If left child is not present then 0
    // is used as data of left child
    if (root->left != nullptr)
        sum += root->left->data;

    // If right child is not present then 0
    // is used as data of right child
    if (root->right != nullptr)
        sum += root->right->data;

    // if the node and both of its children
    // satisfy the property return 1 else 0
    return ((root->data == sum)
            && isSumProperty(root->left)
            && isSumProperty(root->right));
    
}

int main() {
    
    // Create a hard coded tree.
    //         35
    //       /   \
    //      20    15
    //     /  \  /  \
    //   15   5 10   5
    Node* root = new Node(35);
    root->left = new Node(20);
    root->right = new Node(15);
    root->left->left = new Node(15);
    root->left->right = new Node(5);
    root->right->left = new Node(10);
    root->right->right = new Node(5);

    cout << isSumProperty(root) << endl;
    return 0;
}
C
// C Program to check children sum property
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// returns 1 if children sum property holds
// for the given node and both of its children
int isSumProperty(struct Node* root) {

    // If root is NULL or it's a leaf node
    // then return true
    if (root == NULL || (root->left == NULL && root->right == NULL))
        return 1;

    int sum = 0;

    // If left child is not present then 0
    // is used as data of left child
    if (root->left != NULL)
        sum += root->left->data;

    // If right child is not present then 0
    // is used as data of right child
    if (root->right != NULL)
        sum += root->right->data;

    // if the node and both of its children
    // satisfy the property return 1 else 0
    return ((root->data == sum)
            && isSumProperty(root->left)
            && isSumProperty(root->right));
}

struct Node* createNode(int x) {
    struct Node* node = 
      (struct Node*)malloc(sizeof(struct Node));
    node->data = x;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int main() {

    // Create a hard coded tree.
    //         35
    //       /   \
    //      20    15
    //     /  \  /  \
    //   15   5 10   5
    struct Node* root = createNode(35);
    root->left = createNode(20);
    root->right = createNode(15);
    root->left->left = createNode(15);
    root->left->right = createNode(5);
    root->right->left = createNode(10);
    root->right->right = createNode(5);

    printf("%d\n", isSumProperty(root));
    return 0;
}
Java
// java Program to check children sum property
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // returns 1 if children sum property holds
    // for the given node and both of its children
    static int isSumProperty(Node root) {

        // If root is NULL or it's a leaf node
        // then return true
        if (root == null || (root.left == null && root.right == null))
            return 1;

        int sum = 0;

        // If left child is not present then 0
        // is used as data of left child
        if (root.left != null)
            sum += root.left.data;

        // If right child is not present then 0
        // is used as data of right child
        if (root.right != null)
            sum += root.right.data;

        // if the node and both of its children
        // satisfy the property return 1 else 0
        return ((root.data == sum)
                && (isSumProperty(root.left) == 1)
                && (isSumProperty(root.right) == 1))
                ?
                1:0;
    }

    public static void main(String[] args) {

        // Create a hard coded tree.
        //         35
        //       /   \
        //      20    15
        //     /  \  /  \
        //   15   5 10   5
        Node root = new Node(35);
        root.left = new Node(20);
        root.right = new Node(15);
        root.left.left = new Node(15);
        root.left.right = new Node(5);
        root.right.left = new Node(10);
        root.right.right = new Node(5);

        System.out.println(isSumProperty(root));
    }
}
Python
# Python Program to check children sum property
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def isSumProperty(root):

    # If root is None or it's a leaf node
    # then return true
    if root is None or (root.left is None and root.right is None):
        return 1

    sum = 0

    # If left child is not present then 0
    # is used as data of left child
    if root.left is not None:
        sum += root.left.data

    # If right child is not present then 0
    # is used as data of right child
    if root.right is not None:
        sum += root.right.data

    # if the node and both of its children
    # satisfy the property return 1 else 0
    return 1 if (root.data == sum
            and isSumProperty(root.left)
            and isSumProperty(root.right)) else 0

if __name__ == "__main__":
    
    # Create a hard coded tree.
    #         35
    #       /   \
    #      20    15
    #     /  \  /  \
    #   15   5 10   5
    root = Node(35)
    root.left = Node(20)
    root.right = Node(15)
    root.left.left = Node(15)
    root.left.right = Node(5)
    root.right.left = Node(10)
    root.right.right = Node(5)

    print(isSumProperty(root))
C#
// C# Program to check children sum property
using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // returns 1 if children sum property holds
    // for the given node and both of its children
    static int isSumProperty(Node root) {

        // If root is NULL or it's a leaf node
        // then return true
        if (root == null || (root.left == null && root.right == null))
            return 1;

        int sum = 0;

        // If left child is not present then 0
        // is used as data of left child
        if (root.left != null)
            sum += root.left.data;

        // If right child is not present then 0
        // is used as data of right child
        if (root.right != null)
            sum += root.right.data;

        // if the node and both of its children
        // satisfy the property return 1 else 0
        return ((root.data == sum)
                && (isSumProperty(root.left) == 1)
                && (isSumProperty(root.right) == 1))
                ?1:0;
    }

    static void Main(String[] args) {

        // Create a hard coded tree.
        //         35
        //       /   \
        //      20    15
        //     /  \  /  \
        //   15   5 10   5
        Node root = new Node(35);
        root.left = new Node(20);
        root.right = new Node(15);
        root.left.left = new Node(15);
        root.left.right = new Node(5);
        root.right.left = new Node(10);
        root.right.right = new Node(5);

        Console.WriteLine(isSumProperty(root));
    }
}
JavaScript
// JavaScript Program to check children sum property
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// returns 1 if children sum property holds
// for the given node and both of its children
function isSumProperty(root) {

    // If root is NULL or it's a leaf node
    // then return true
    if (root === null || (root.left === null && root.right === null))
        return 1;

    let sum = 0;

    // If left child is not present then 0
    // is used as data of left child
    if (root.left !== null)
        sum += root.left.data;

    // If right child is not present then 0
    // is used as data of right child
    if (root.right !== null)
        sum += root.right.data;

    // if the node and both of its children
    // satisfy the property return 1 else 0
    return (root.data === sum
            && (isSumProperty(root.left) === 1)
            && (isSumProperty(root.right) === 1))
            ?1:0;
}

// Create a hard coded tree.
//         35
//       /   \
//      20    15
//     /  \  /  \
//   15   5 10   5
let root = new Node(35);
root.left = new Node(20);
root.right = new Node(15);
root.left.left = new Node(15);
root.left.right = new Node(5);
root.right.left = new Node(10);
root.right.right = new Node(5);

console.log(isSumProperty(root));

Output
1

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(h), where h is the height of the tree.

[Alternate Approach] Using Queue – O(n) Time and O(n) Space:

The idea is to traverse the tree using level order approach. For each node, check if it satisfies children sum property. If it does, then push its children nodes into the queue. Otherwise return 0.

Below is the implementation of this approach:

C++
// C++ Program to check children sum property
#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node* left;
        Node* right;
        Node (int x) {
            data = x;
            left = nullptr;
            right = nullptr;
        }
};

// returns 1 if children sum property holds
// for the given node and both of its children
int isSumProperty(Node* root) {

    // If root is NULL
    // then return true
    if (root == nullptr)
        return 1;
        
    queue<Node*> q;
    q.push(root);
    
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();
        
        // if this node is a leaf node, 
        // then continue
        if (curr->left == nullptr &&
            curr->right == nullptr)
            continue;
        
        int sum = 0;
        
        // If left child is not present then 0
        // is used as data of left child
        if (curr->left != nullptr) {
            sum += curr->left->data;
        }
        
        // If right child is not present then 0
        // is used as data of right child
        if (curr->right != nullptr) {
            sum += curr->right->data;
        }
        
        // if current node does not
        // follow the property, then
        // return 0.
        if (curr->data != sum) 
            return 0;
            
        // Push the left child node
        if (curr->left != nullptr)
            q.push(curr->left);
            
        // Push the right child node
        if (curr->right != nullptr)
            q.push(curr->right);
    }
        
    return 1;
}

int main() {
    
    // Create a hard coded tree.
    //         35
    //       /   \
    //      20    15
    //     /  \  /  \
    //   15   5 10   5
    Node* root = new Node(35);
    root->left = new Node(20);
    root->right = new Node(15);
    root->left->left = new Node(15);
    root->left->right = new Node(5);
    root->right->left = new Node(10);
    root->right->right = new Node(5);

    cout << isSumProperty(root) << endl;
    return 0;
}
Java
// Java Program to check children sum property
import java.util.LinkedList;
import java.util.Queue;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // returns 1 if children sum property holds
    // for the given node and both of its children
    static int isSumProperty(Node root) {

        // If root is NULL
        // then return true
        if (root == null)
            return 1;

        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            // if this node is a leaf node, 
            // then continue
            if (curr.left == null && curr.right == null)
                continue;

            int sum = 0;

            // If left child is not present then 0
            // is used as data of left child
            if (curr.left != null) {
                sum += curr.left.data;
            }

            // If right child is not present then 0
            // is used as data of right child
            if (curr.right != null) {
                sum += curr.right.data;
            }

            // if current node does not
            // follow the property, then
            // return 0.
            if (curr.data != sum)
                return 0;

            // Push the left child node
            if (curr.left != null)
                q.add(curr.left);

            // Push the right child node
            if (curr.right != null)
                q.add(curr.right);
        }

        return 1;
    }

    public static void main(String[] args) {

        // Create a hard coded tree.
        //         35
        //       /   \
        //      20    15
        //     /  \  /  \
        //   15   5 10   5
        Node root = new Node(35);
        root.left = new Node(20);
        root.right = new Node(15);
        root.left.left = new Node(15);
        root.left.right = new Node(5);
        root.right.left = new Node(10);
        root.right.right = new Node(5);

        System.out.println(isSumProperty(root));
    }
}
Python
# Python Program to check children sum property
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def is_sum_property(root):

    # If root is None
    # then return true
    if root is None:
        return 1

    q = deque([root])

    while q:
        curr = q.popleft()

        # if this node is a leaf node, 
        # then continue
        if curr.left is None and curr.right is None:
            continue

        sum_val = 0

        # If left child is not present then 0
        # is used as data of left child
        if curr.left is not None:
            sum_val += curr.left.data

        # If right child is not present then 0
        # is used as data of right child
        if curr.right is not None:
            sum_val += curr.right.data

        # if current node does not
        # follow the property, then
        # return 0.
        if curr.data != sum_val:
            return 0

        # Push the left child node
        if curr.left is not None:
            q.append(curr.left)

        # Push the right child node
        if curr.right is not None:
            q.append(curr.right)

    return 1

if __name__ == "__main__":
    
    # Create a hard coded tree.
    #         35
    #       /   \
    #      20    15
    #     /  \  /  \
    #   15   5 10   5
    root = Node(35)
    root.left = Node(20)
    root.right = Node(15)
    root.left.left = Node(15)
    root.left.right = Node(5)
    root.right.left = Node(10)
    root.right.right = Node(5)

    print(is_sum_property(root))
C#
// C# Program to check children sum property
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // returns 1 if children sum property holds
    // for the given node and both of its children
    static int isSumProperty(Node root) {

        // If root is NULL
        // then return true
        if (root == null)
            return 1;

        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // if this node is a leaf node, 
            // then continue
            if (curr.left == null && curr.right == null)
                continue;

            int sum = 0;

            // If left child is not present then 0
            // is used as data of left child
            if (curr.left != null) {
                sum += curr.left.data;
            }

            // If right child is not present then 0
            // is used as data of right child
            if (curr.right != null) {
                sum += curr.right.data;
            }

            // if current node does not
            // follow the property, then
            // return 0.
            if (curr.data != sum)
                return 0;

            // Push the left child node
            if (curr.left != null)
                q.Enqueue(curr.left);

            // Push the right child node
            if (curr.right != null)
                q.Enqueue(curr.right);
        }

        return 1;
    }

    static void Main(string[] args) {

        // Create a hard coded tree.
        //         35
        //       /   \
        //      20    15
        //     /  \  /  \
        //   15   5 10   5
        Node root = new Node(35);
        root.left = new Node(20);
        root.right = new Node(15);
        root.left.left = new Node(15);
        root.left.right = new Node(5);
        root.right.left = new Node(10);
        root.right.right = new Node(5);

        Console.WriteLine(isSumProperty(root));
    }
}
JavaScript
// JavaScript Program to check children sum property
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// returns 1 if children sum property holds
// for the given node and both of its children
function isSumProperty(root) {

    // If root is NULL
    // then return true
    if (root === null)
        return 1;

    let q = [];
    q.push(root);

    while (q.length > 0) {
        let curr = q.shift();

        // if this node is a leaf node, 
        // then continue
        if (curr.left === null && curr.right === null)
            continue;

        let sum = 0;

        // If left child is not present then 0
        // is used as data of left child
        if (curr.left !== null) {
            sum += curr.left.data;
        }

        // If right child is not present then 0
        // is used as data of right child
        if (curr.right !== null) {
            sum += curr.right.data;
        }

        // if current node does not
        // follow the property, then
        // return 0.
        if (curr.data !== sum)
            return 0;

        // Push the left child node
        if (curr.left !== null)
            q.push(curr.left);

        // Push the right child node
        if (curr.right !== null)
            q.push(curr.right);
    }

    return 1;
}

// Create a hard coded tree.
//         35
//       /   \
//      20    15
//     /  \  /  \
//   15   5 10   5
let root = new Node(35);
root.left = new Node(20);
root.right = new Node(15);
root.left.left = new Node(15);
root.left.right = new Node(5);
root.right.left = new Node(10);
root.right.right = new Node(5);

console.log(isSumProperty(root));

Output
1

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)



Next Article
Article Tags :
Practice Tags :

Similar Reads