Check if a given binary tree is Sum Tree

Posted by N.K. Chauhan on Mar 31, 2024

A binary tree is given, the task is to check if, it is a Sum Tree or not.

A SumTree 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 SumTree and the sum of an empty tree can be considered as 0.

A leaf node is also considered as SumTree.


Solutions

Method 1: Recursion

Get the sum of nodes in the left subtree and right subtree using "sum()".

Check if the sum calculated for both left and right sub-trees is equal to the root's data.

Also, recursively check if the left and right subtrees are Sum Trees.

Complexity
The time complexity of this solution is O(n2) and space complexity is O(n) due to auxiliary stack.

Related


Create a mirror tree from a given binary tree

Find the diameter or width of a binary tree

Print/Traverse a Binary Tree in Zigzag Order

Write a program to print height/depth of a Binary Tree

Pre-order Tree Traversal - Iterative and Recursive

Level Order or Breadth First traversal of Binary Tree

Print the left view of a binary tree

In-order Tree Traversal - Iterative and Recursive

Print diagonal traversal of a binary tree

Print Nodes in Top View of a Binary Tree

Print a Binary Tree in Vertical Order