Write a function that returns true if the given Binary Tree is SumTree else false. A SumTree is a Binary Tree where the value of a node is equal to sum of the nodes present in its left subtree and right subtree. An empty tree is SumTree and sum of an empty tree can be considered as 0. A leaf node is also considered as SumTree.
Following is an example of SumTree.
26 / \ 10 3 / \ \ 4 6 3
Method 1 ( Simple )
Get the sum of nodes in left subtree and right subtree. Check if the sum calculated is equal to root’s data. Also, recursively check if the left and right subtrees are SumTrees.
The given tree is a SumTree
Time Complexity: O(n^2) in worst case. Worst case occurs for a skewed tree.
Method 2 ( Tricky )
The Method 1 uses sum() to get the sum of nodes in left and right subtrees. The method 2 uses following rules to get the sum directly.
1) If the node is a leaf node then sum of subtree rooted with this node is equal to value of this node.
2) If the node is not a leaf node then sum of subtree rooted with this node is twice the value of this node (Assuming that the tree rooted with this node is SumTree).
The given tree is a sum tree
Time Complexity: O(n)
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree | Set 1
- Check whether a binary tree is a full binary tree or not
- Check whether a given binary tree is skewed binary tree or not?
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Check if the given n-ary tree is a binary tree
- A program to check if a binary tree is BST or not
- Check whether a given binary tree is perfect or not
- Check if a given Binary Tree is Heap
- Check if a Binary Tree (not BST) has duplicate values
- Check for Children Sum Property in a Binary Tree
- Check whether every node of binary tree has a value K on itself or its any immediate neighbours
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's