

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check for Children Sum Property in a Binary Tree in C++
Suppose we have a binary tree. The binary tree is valid when it meets the following property.
- Each node should contain data value same as the sum of left and right children values. If there are no children at any side, then it will be treated as 0.
Suppose a tree is present like below, which meets the given property.
There is no such trick to check this, we have to traverse the tree recursively, if the node and both of its children satisfies the property then return true, otherwise false.
Example
#include <iostream> using namespace std; class node { public: int data; node* left; node* right; }; bool isValidBinaryTree(node* nd) { int left_data = 0, right_data = 0; if(nd == NULL || (nd->left == NULL && nd->right == NULL)) return 1; else{ if(nd->left != NULL) left_data = nd->left->data; if(nd->right != NULL) right_data = nd->right->data; if((nd->data == left_data + right_data)&& isValidBinaryTree(nd->left) && isValidBinaryTree(nd->right)) return true; else return false; } } node* getNode(int data) { node* newNode = new node(); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } int main() { node *root = getNode(10); root->left = getNode(8); root->right = getNode(2); root->left->left = getNode(3); root->left->right = getNode(5); root->right->right = getNode(2); if(isValidBinaryTree(root)) cout << "The tree satisfies the children sum property "; else cout << "The tree does not satisfy the children sum property "; }
Output
The tree satisfies the children sum property
- Related Questions & Answers
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property in C++
- Maximum parent children sum in Binary tree in C++
- Check if a binary tree is subtree of another binary tree in C++
- Diagonal Sum of a Binary Tree in C++?
- Binary Search Tree to Greater Sum Tree in C++
- Maximum Path Sum in a Binary Tree in C++
- Check Completeness of a Binary Tree in C++
- How to check whether a binary tree has the given path sum in C#?
- Binary Tree Maximum Path Sum in Python
- Maximum Level Sum of a Binary Tree in C++
- Maximum spiral sum in Binary Tree in C++
- Maximum Sum BST in Binary Tree in C++
- How to check whether a binary tree is a valid binary search tree using recursion in C#?
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
- Print all k-sum paths in a binary tree in C++
Advertisements