A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as 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 : 3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5
Source : Amazon Interview Experience Set-323
Kindly note that this problem is significantly different from finding k-sum path from root to leaves. Here each node can be treated as root, hence the path can start and end at any node.
The basic idea to solve the problem is to do a preorder traversal of the given tree. We also need a container (vector) to keep track of the path that led to that node. At each node we check if there are any path that sums to k, if any we print the path and proceed recursively to print each path.
Below is the implementation of the same.
3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5
This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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.
- Print all the Paths of a Binary Tree whose XOR is non-zero
- Print Palindromic Paths of 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
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Print all paths of the Binary Tree with maximum element in each path greater than or equal to K
- Count even paths in Binary Tree
- Count all k-sum paths in a Binary Tree
- Count of Fibonacci paths in a Binary tree
- Count of exponential paths in a Binary Tree
- Count of paths in given Binary Tree with odd bitwise AND for Q queries
- Count of root to leaf paths in a Binary Tree that form an AP
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Root to leaf paths having equal lengths in a Binary Tree
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print all K-sum levels in a Binary Tree
- Print Right View of a Binary Tree
- Print Binary Tree in 2-Dimensions
- Print all Prime Levels of a Binary Tree