Check if a given Binary Tree is Sum Tree
Last Updated :
19 Sep, 2024
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 considered a Sum Tree.
Example:
Input:
Output: True
Explanation: The above tree follows the property of Sum Tree.
Input:
Output: False
Explanation: The above tree doesn't follows the property of Sum Tree as 6 + 2 != 10.
[Naive Approach] By Checking Every Node - O(n^2) Time and O(h) Space:
The idea is to get the sum in the left subtree and right subtree for each node and compare it with the node's value. Also recursively check if the left and right subtree are sum trees.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree
// is sum tree or not
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// A utility function to get the sum
// of values in tree
int sum(Node *root) {
if (root == NULL)
return 0;
return sum(root->left) + root->data +
sum(root->right);
}
// Returns 1 if sum property holds for
// the given node and both of its children
bool isSumTree(Node* root) {
int ls, rs;
// If root is NULL or it's a leaf
// node then return true
if (root == nullptr ||
(root->left == nullptr &&
root->right == nullptr))
return true;
// Get sum of nodes in left and
// right subtrees
ls = sum(root->left);
rs = sum(root->right);
// If the root and both of its
// children satisfy the property
// return true else false
if ((root->data == ls + rs) &&
isSumTree(root->left) &&
isSumTree(root->right))
return true;
return false;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node* root = new Node(26);
root->left = new Node(10);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(6);
root->right->right = new Node(3);
if (isSumTree(root))
cout << "True";
else
cout << "False";
return 0;
}
C
// C program to check if Binary tree
// is sum tree or not
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// A utility function to get the sum of values in tree
int sum(struct Node* root) {
if (root == NULL)
return 0;
return sum(root->left) + root->data +
sum(root->right);
}
// Returns 1 if sum property holds for the
// given node and both of its children
int isSumTree(struct Node* root) {
int ls, rs;
// If root is NULL or it's a leaf node
// then return true
if (root == NULL || (root->left == NULL &&
root->right == NULL))
return 1;
// Get sum of nodes in left and right subtrees
ls = sum(root->left);
rs = sum(root->right);
// If the root and both of its children satisfy
// the property, return true else false
if ((root->data == ls + rs) &&
isSumTree(root->left) && isSumTree(root->right))
return 1;
return 0;
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->left = node->right = NULL;
return node;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
struct Node* root = createNode(26);
root->left = createNode(10);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(6);
root->right->right = createNode(3);
if (isSumTree(root))
printf("True");
else
printf("False");
return 0;
}
Java
// Java program to check if Binary tree
// is sum tree or not
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
// A utility function to get the sum of values in tree
class GfG {
static int sum(Node root) {
if (root == null)
return 0;
return sum(root.left) + root.data +
sum(root.right);
}
// Returns true if sum property holds for the
// given node and both of its children
static boolean isSumTree(Node root) {
int ls, rs;
// If root is null or it's a leaf node
// then return true
if (root == null || (root.left == null &&
root.right == null))
return true;
// Get sum of nodes in left and right subtrees
ls = sum(root.left);
rs = sum(root.right);
// If the root and both of its children satisfy
// the property, return true else false
return (root.data == ls + rs) &&
isSumTree(root.left) && isSumTree(root.right);
}
public static void main(String[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python3 program to implement
# the above approach
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# A utility function to get the sum of values in tree
def sum_tree(root):
if root is None:
return 0
return sum_tree(root.left) + root.data + sum_tree(root.right)
# Returns True if sum property holds for the given
# node and both of its children
def is_sum_tree(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 True
# Get sum of nodes in left and right subtrees
ls = sum_tree(root.left)
rs = sum_tree(root.right)
# If the root and both of its children
# satisfy the property, return True else False
return root.data == ls + rs and \
is_sum_tree(root.left) and \
is_sum_tree(root.right)
if __name__ == "__main__":
# create hard coded tree
# 26
# / \
# 10 3
# / \ \
# 4 6 3
root = Node(26)
root.left = Node(10)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(6)
root.right.right = Node(3)
if is_sum_tree(root):
print("True")
else:
print("False")
C#
// C# program to check if Binary tree
// is sum tree or not
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// A utility function to get the sum of values in tree
static int Sum(Node root) {
if (root == null)
return 0;
return Sum(root.left) + root.data +
Sum(root.right);
}
// Returns true if sum property holds for
// the given node and both of its children
static bool IsSumTree(Node root) {
int ls, rs;
// If root is null or it's a leaf node then return true
if (root == null || (root.left == null &&
root.right == null))
return true;
// Get sum of nodes in left and right subtrees
ls = Sum(root.left);
rs = Sum(root.right);
// If the root and both of its children
// satisfy the property, return true else false
return (root.data == ls + rs) &&
IsSumTree(root.left) &&
IsSumTree(root.right);
}
static void Main(string[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (IsSumTree(root))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to check if Binary tree
// is sum tree or not
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}
// A utility function to get the sum of values in tree
function sum(root) {
if (root == null)
return 0;
return sum(root.left) + root.data + sum(root.right);
}
// Returns true if sum property holds for the given
// node and both of its children
function isSumTree(root) {
// If root is null or it's a leaf node then return true
if (root == null || (root.left == null && root.right == null))
return true;
// Get sum of nodes in left and right subtrees
let ls = sum(root.left);
let rs = sum(root.right);
// If the root and both of its children satisfy the
// property, return true else false
return root.data == ls + rs &&
isSumTree(root.left) &&
isSumTree(root.right);
}
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root)) {
console.log("True");
} else {
console.log("False");
}
Time Complexity: O(n^2), where n are the number of nodes in binary tree.
Auxiliary Space: O(h)
[Expected Approach] Calculating left and right subtree sum directly - O(n) Time and O(h) Space:
The idea is to first check if left and right subtrees are sum trees. If they are, then the sum of left and right subtrees can easily be obtained in O(1) time.
Step by Step implementation:
- For a given root node, recursively check if left subtree and right subtree are sum trees. If one of them or both are not sum tree, simply return false.
- If both of them are sum trees, then we can find the sum of left subtree and right subtree in O(1) using the following conditions:
- If the root is null, then the sum is 0.
- If the root is a leaf node, then sum is equal to root's value.
- Otherwise, the sum if equal to twice of root's value. This is because this subtree is a sum tree. So the sum of this subtree's subtree is equal to root's value. So the total sum becomes 2*root->val.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree
// is sum tree or not
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Utility function to check if
// the given node is leaf or not
bool isLeaf(Node *node) {
if(node == nullptr)
return false;
if(node->left == nullptr && node->right == nullptr)
return true;
return false;
}
bool isSumTree(Node* root) {
int ls, rs;
// If node is NULL or it's a leaf node then
// return true
if(root == nullptr || isLeaf(root))
return true;
// If the left subtree and right subtree are sum trees,
// then we can find subtree sum in O(1).
if( isSumTree(root->left) && isSumTree(root->right)) {
// Get the sum of nodes in left subtree
if(root->left == nullptr)
ls = 0;
else if(isLeaf(root->left))
ls = root->left->data;
else
ls = 2 * (root->left->data);
// Get the sum of nodes in right subtree
if(root->right == nullptr)
rs = 0;
else if(isLeaf(root->right))
rs = root->right->data;
else
rs = 2 * (root->right->data);
// If root's data is equal to sum of nodes in left
// and right subtrees then return true else return false
return(root->data == ls + rs);
}
// if either of left or right subtree is not
// sum tree, then return false.
return false;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node* root = new Node(26);
root->left = new Node(10);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(6);
root->right->right = new Node(3);
if (isSumTree(root))
cout << "True";
else
cout << "False";
return 0;
}
C
// C program to check if Binary tree
// is sum tree or not
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Utility function to check if the given node is leaf or not
int isLeaf(struct Node* node) {
if (node == NULL)
return 0;
if (node->left == NULL && node->right == NULL)
return 1;
return 0;
}
int isSumTree(struct Node* root) {
int ls, rs;
// If node is NULL or it's a leaf node then return true
if (root == NULL || isLeaf(root))
return 1;
// If the left subtree and right subtree are sum trees,
// then we can find subtree sum in O(1).
if (isSumTree(root->left) && isSumTree(root->right)) {
// Get the sum of nodes in left subtree
if (root->left == NULL)
ls = 0;
else if (isLeaf(root->left))
ls = root->left->data;
else
ls = 2 * (root->left->data);
// Get the sum of nodes in right subtree
if (root->right == NULL)
rs = 0;
else if (isLeaf(root->right))
rs = root->right->data;
else
rs = 2 * (root->right->data);
// If root's data is equal to sum of nodes in left
// and right subtrees then return true else return false
return (root->data == ls + rs);
}
// if either of left or right subtree
// is not sum tree, then return false.
return 0;
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->left = node->right = NULL;
return node;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
struct Node* root = createNode(26);
root->left = createNode(10);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(6);
root->right->right = createNode(3);
if (isSumTree(root))
printf("True");
else
printf("False");
return 0;
}
Java
// Java program to check if Binary tree
// is sum tree or not
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Utility function to check if the given node is leaf or not
static boolean isLeaf(Node node) {
if (node == null)
return false;
if (node.left == null && node.right == null)
return true;
return false;
}
static boolean isSumTree(Node root) {
int ls, rs;
// If node is null or it's a leaf node then return true
if (root == null || isLeaf(root))
return true;
// If the left subtree and right subtree are sum trees,
// then we can find subtree sum in O(1).
if (isSumTree(root.left) && isSumTree(root.right)) {
// Get the sum of nodes in left subtree
if (root.left == null)
ls = 0;
else if (isLeaf(root.left))
ls = root.left.data;
else
ls = 2 * (root.left.data);
// Get the sum of nodes in right subtree
if (root.right == null)
rs = 0;
else if (isLeaf(root.right))
rs = root.right.data;
else
rs = 2 * (root.right.data);
// If root's data is equal to sum of nodes in left
// and right subtrees then return true else return false
return root.data == ls + rs;
}
// if either of left or right subtree is not
// sum tree, then return false.
return false;
}
public static void main(String[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python3 program to check if
# Binary tree is sum tree or not
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Utility function to check if the
# given node is leaf or not
def is_leaf(node):
if node is None:
return False
if node.left is None and node.right is None:
return True
return False
def is_sum_tree(root):
# If node is None or it's a leaf node then return True
if root is None or is_leaf(root):
return True
# If the left subtree and right subtree are sum trees,
# then we can find subtree sum in O(1).
if is_sum_tree(root.left) and is_sum_tree(root.right):
# Get the sum of nodes in left subtree
if root.left is None:
ls = 0
elif is_leaf(root.left):
ls = root.left.data
else:
ls = 2 * root.left.data
# Get the sum of nodes in right subtree
if root.right is None:
rs = 0
elif is_leaf(root.right):
rs = root.right.data
else:
rs = 2 * root.right.data
# If root's data is equal to sum of nodes in left
# and right subtrees then return True else return False
return root.data == ls + rs
# if either of left or right subtree is not sum
# tree, then return False.
return False
if __name__ == "__main__":
# create hard coded tree
# 26
# / \
# 10 3
# / \ \
# 4 6 3
root = Node(26)
root.left = Node(10)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(6)
root.right.right = Node(3)
if is_sum_tree(root):
print("True")
else:
print("False")
C#
// C# program to check if Binary tree
// is sum tree or not
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Utility function to check if the given
// node is leaf or not
static bool IsLeaf(Node node) {
if (node == null)
return false;
if (node.left == null &&
node.right == null)
return true;
return false;
}
static bool IsSumTree(Node root) {
int ls, rs;
// If node is null or it's a leaf node
// then return true
if (root == null || IsLeaf(root))
return true;
// If the left subtree and right subtree are sum trees,
// then we can find subtree sum in O(1).
if (IsSumTree(root.left) && IsSumTree(root.right)) {
// Get the sum of nodes in left subtree
if (root.left == null)
ls = 0;
else if (IsLeaf(root.left))
ls = root.left.data;
else
ls = 2 * root.left.data;
// Get the sum of nodes in right subtree
if (root.right == null)
rs = 0;
else if (IsLeaf(root.right))
rs = root.right.data;
else
rs = 2 * root.right.data;
// If root's data is equal to sum of
// nodes in left and right subtrees
// then return true else return false
return root.data == ls + rs;
}
// if either of left or right subtree is
// not sum tree, then return false.
return false;
}
static void Main(string[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (IsSumTree(root))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Utility function to check if the given
// node is leaf or not
function isLeaf(node) {
if (node === null) return false;
if (node.left === null && node.right === null) return true;
return false;
}
function isSumTree(root) {
let ls, rs;
// If node is null or it's a leaf node then return true
if (root === null || isLeaf(root)) return true;
// If the left subtree and right subtree are sum trees,
// then we can find subtree sum in O(1).
if (isSumTree(root.left) && isSumTree(root.right)) {
// Get the sum of nodes in left subtree
if (root.left === null) ls = 0;
else if (isLeaf(root.left)) ls = root.left.data;
else ls = 2 * root.left.data;
// Get the sum of nodes in right subtree
if (root.right === null) rs = 0;
else if (isLeaf(root.right)) rs = root.right.data;
else rs = 2 * root.right.data;
// If root's data is equal to sum of nodes in left
// and right subtrees then return true else return false
return root.data === ls + rs;
}
// if either of left or right subtree is not
// sum tree, then return false.
return false;
}
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root)) console.log("True");
else console.log("False");
Time Complexity: O(n), where n are the number of nodes in binary tree.
Auxiliary Space: O(h)
[Alternate Approach] Using post order traversal - O(n) Time and O(h) Space:
The idea is recursively check if the left and right subtrees are sum trees. If a subtree is sum tree, it will return the sum of its root node, left tree and right tree. Otherwise it will return -1.
Step by step implementation:
- For each current node, recursively check the left and right subtree for sum tree.
- If the subtree is sum tree, it will return the sum of its root node, left tree and right tree.
- Compare the sum of left subtree and right subtree with the root node. If they are equal, return sum of root node, left subtree and right subtree. Otherwise return -1.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree
// is sum tree or not
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// returns sum if tree is SumTree
// else return -1
int isSumTree(Node* root) {
if(root == nullptr)
return 0;
// If node is leaf node, return its value.
if (root->left == nullptr && root->right == nullptr)
return root->data;
// Calculate left subtree sum
int ls = isSumTree(root->left);
// if left subtree is not sum tree,
// return -1.
if(ls == -1)
return -1;
// Calculate right subtree sum
int rs = isSumTree(root->right);
// if right subtree is not sum tree,
// return -1.
if(rs == -1)
return -1;
if(ls + rs == root->data)
return ls + rs + root->data;
else
return -1;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node* root = new Node(26);
root->left = new Node(10);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(6);
root->right->right = new Node(3);
if (isSumTree(root)!=-1)
cout << "True";
else
cout << "False";
return 0;
}
C
// C program to check if Binary tree
// is sum tree or not
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// returns sum if tree is SumTree
// else return -1
int isSumTree(struct Node* root) {
if (root == NULL)
return 0;
// If node is leaf node, return its value.
if (root->left == NULL && root->right == NULL)
return root->data;
// Calculate left subtree sum
int ls = isSumTree(root->left);
// if left subtree is not sum tree, return -1.
if (ls == -1)
return -1;
// Calculate right subtree sum
int rs = isSumTree(root->right);
// if right subtree is not sum tree, return -1.
if (rs == -1)
return -1;
if (ls + rs == root->data)
return ls + rs + root->data;
else
return -1;
}
struct Node* createNode(int x) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = x;
node->left = node->right = NULL;
return node;
}
int main() {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
struct Node* root = createNode(26);
root->left = createNode(10);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(6);
root->right->right = createNode(3);
if (isSumTree(root) != -1)
printf("True");
else
printf("False");
return 0;
}
Java
// Java program to check if Binary tree
// is sum tree or not
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// returns sum if tree is SumTree
// else return -1
static int isSumTree(Node root) {
if (root == null)
return 0;
// If node is leaf node, return its value.
if (root.left == null && root.right == null)
return root.data;
// Calculate left subtree sum
int ls = isSumTree(root.left);
// if left subtree is not sum tree, return -1.
if (ls == -1)
return -1;
// Calculate right subtree sum
int rs = isSumTree(root.right);
// if right subtree is not sum tree, return -1.
if (rs == -1)
return -1;
if (ls + rs == root.data)
return ls + rs + root.data;
else
return -1;
}
public static void main(String[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root) != -1)
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python3 program to check if
# Binary tree is sum tree or not
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# returns sum if tree is SumTree
# else return -1
def is_sum_tree(root):
if root is None:
return 0
# If node is leaf node, return its value.
if root.left is None and root.right is None:
return root.data
# Calculate left subtree sum
ls = is_sum_tree(root.left)
# if left subtree is not sum tree, return -1.
if ls == -1:
return -1
# Calculate right subtree sum
rs = is_sum_tree(root.right)
# if right subtree is not sum tree, return -1.
if rs == -1:
return -1
if ls + rs == root.data:
return ls + rs + root.data
else:
return -1
if __name__ == "__main__":
# create hard coded tree
# 26
# / \
# 10 3
# / \ \
# 4 6 3
root = Node(26)
root.left = Node(10)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(6)
root.right.right = Node(3)
if is_sum_tree(root) != -1:
print("True")
else:
print("False")
C#
// C# program to check if Binary tree
// is sum tree or not
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// returns sum if tree is SumTree
// else return -1
static int IsSumTree(Node root) {
if (root == null)
return 0;
// If node is leaf node, return its value.
if (root.left == null && root.right == null)
return root.data;
// Calculate left subtree sum
int ls = IsSumTree(root.left);
// if left subtree is not sum tree, return -1.
if (ls == -1)
return -1;
// Calculate right subtree sum
int rs = IsSumTree(root.right);
// if right subtree is not sum tree, return -1.
if (rs == -1)
return -1;
if (ls + rs == root.data)
return ls + rs + root.data;
else
return -1;
}
static void Main(string[] args) {
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
Node root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (IsSumTree(root) != -1)
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript program to check if
// Binary tree is sum tree or not
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// returns sum if tree is SumTree
// else return -1
function isSumTree(root) {
if (root === null) return 0;
// If node is leaf node, return its value.
if (root.left === null && root.right === null) return root.data;
// Calculate left subtree sum
const ls = isSumTree(root.left);
// if left subtree is not sum tree, return -1.
if (ls === -1) return -1;
// Calculate right subtree sum
const rs = isSumTree(root.right);
// if right subtree is not sum tree, return -1.
if (rs === -1) return -1;
if (ls + rs === root.data) return ls + rs + root.data;
else return -1;
}
// create hard coded tree
// 26
// / \
// 10 3
// / \ \
// 4 6 3
let root = new Node(26);
root.left = new Node(10);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(6);
root.right.right = new Node(3);
if (isSumTree(root) !== -1) console.log("True");
else console.log("False");
Time Complexity: O(n), where n are the number of nodes in binary tree.
Auxiliary Space: O(h)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem