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 whether a given binary tree is skewed binary tree or not?
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- 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 using preorder traversal : Iterative
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- 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
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Binary Tree to Binary Search Tree Conversion
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Binary Tree | Set 3 (Types of Binary Tree)
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)