Given a binary tree and an integer k. The task is to count the number of paths in the tree with the sum of the nodes equals to k.
A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node, and negative numbers can also be there in the tree.
Input : k = 5 Root of below binary tree: 1 / \ 3 -1 / \ / \ 2 1 4 5 / / \ \ 1 1 2 6 Output : No of paths with sum equals to 5 are: 8 3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5 Input : k = 3 1 / \ 2 -1 / \ / 1 2 3 / \ 2 5 Output : No of paths with sum equals to 3 are : 4
The implementation of printing paths with path sum equal to k is already discussed in this post using vector. However, storing in vector and recursively moving increases both space and time complexity if we just want to store the count of such paths
- We will be using a unordered map which will be filled with various path sum.
- For every node we will check if current sum and root’s value equal to k or not. If the sum equals to k then increment the required answer by one.
- Then we will add all those path sum in map which differs from current sum+root->data value by a constant integer k.
- Then we will be inserting the current sum + root->data value in the map.
- We will recursively check for left and right subtrees of current root
- After the right subtree is also traversed we will remove the current sum + root->data value from the map so that it is not taken into consideration in further traversals of other nodes other than the current root’s
Below is the implementation of the above approach:
No of paths with sum equals to 3 are : 4
- Print all k-sum paths in a binary tree
- Print all the paths from root, with a specified sum in Binary tree
- Given a binary tree, print all root-to-leaf paths
- Root to leaf paths having equal lengths in a Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Count the Number of Binary Search Trees present in a Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Count pairs in a binary tree whose sum is equal to a given value x
- Count nodes with two children at level L in a Binary Tree
- Program to count leaf nodes in a binary tree
- Count half nodes in a Binary tree (Iterative and Recursive)
- Iterative program to count leaf nodes in a Binary Tree
- Count full nodes in a Binary tree (Iterative and Recursive)
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.