Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Check if a Binary Tree is BST or not
Next article icon

Check for Children Sum Property in a Binary Tree

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Table of Content

  • [Expected Approach] Using Recursion – O(n) Time and O(h) Space
  • [Alternate Approach] Using Queue – O(n) Time and O(n) Space

[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
Check if a Binary Tree is BST or not
author
kartik
Improve
Article Tags :
  • DSA
  • Tree
  • Accolite
  • Amazon
Practice Tags :
  • Accolite
  • Amazon
  • Tree

Similar Reads

  • Iterative approach to check for children sum property in a Binary Tree
    Given a binary tree, write a function that returns true if the tree satisfies below property:For every node, data value must be equal to the sum of data values in left and right children. Consider data value as 0 for NULL children.Examples: Input : 10 / \ 8 2 / \ \ 3 5 2 Output : Yes Input : 5 / \ -
    8 min read
  • Maximum parent children sum in Binary tree
    Given a Binary Tree, find the maximum sum in a binary tree by adding the parent with its children. Exactly three Node needs to be added. If the tree does not have a node with both of its children as not NULL, return 0. We simply traverse the tree and find the Node that has the maximum sum. We need t
    5 min read
  • Check if a given Binary Tree is Sum Tree
    Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is Sum Tree and the sum of an empty tree can be considered as 0. A leaf node is also cons
    15+ min read
  • Check if a Binary Tree is BST or not
    Given the root of a binary tree. Check whether it is a Binary Search Tree or not. A Binary Search Tree (BST) is a node-based binary tree data structure with the following properties. All keys in the left subtree are smaller than the root and all keys in the right subtree are greater.Both the left an
    15+ min read
  • Check if two nodes are cousins in a Binary Tree
    Given a binary tree (having distinct node values) root and two node values. The task is to check whether the two nodes with values a and b are cousins.Note: Two nodes of a binary tree are cousins if they have the same depth with different parents. Example: Input: a = 5, b = 4 Output: TrueExplanation
    13 min read
  • Check if the given n-ary tree is a binary tree
    Given an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multip
    6 min read
  • Check if a given Binary Tree is a Heap
    Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).Every node’s v
    15+ min read
  • Check whether a given binary tree is perfect or not
    Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.Note: A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.A Perfect Binary Tree of height h has 2h – 1 nodes.Examples: Input:
    14 min read
  • Check if a Binary Tree is an Even-Odd Tree or not
    Given a Binary Tree, the task is to check if the binary tree is an Even-Odd binary tree or not. A Binary Tree is called an Even-Odd Tree when all the nodes which are at even levels have even values (assuming root to be at level 0) and all the nodes which are at odd levels have odd values. Examples:
    15+ min read
  • Check if two binary trees are mirror | Set 3
    Given two arrays, A[] and B[] consisting of M pairs, representing the edges of the two binary trees of N distinct nodes according to the level order traversal, the task is to check if trees are the mirror images of each other. Examples: Input: N = 6, M = 5, A[][2] = {{1, 5}, {1, 4}, {5, 7}, {5, 8},
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences