Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Check If Binary Tree Is Sum Tree Or Not

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
25 upvotes
Asked in companies
AdobeGoldman SachsAmazon

Problem statement

You are given an arbitrary binary tree consisting of N nodes where each node is associated with a certain value. You need to check whether the given tree is a sum tree or not.

A binary tree is a sum tree if the value of each node is equal to the sum of nodes present in the left and the right subtree. An empty tree is a sum tree with 0 sums. A leaf node is also considered a sum tree with a sum equal to the value of the leaf node.

Detailed explanation ( Input/output format, Notes, Images )

Sample Input 1 :

2
3 1 2 -1 -1 -1 -1
3 -1 1 2 -1 -1 -1

Sample Output 1 :

true
false
Explanation for sample input 1 :
For the first test case, the given tree is

For each level, we can see that the value of each node is equal to the sum of the left and the right subtree.

For the second test case, the given tree is

We can see that the sum of a subtree of a node with root 1 is not equal to the value of the node. Hence, the answer is ‘false’.
Full screen
Console