Input: 2 / \ 1 6 / \ 5 7 / 3 \ 4 sum = 8 Output: 1 7 2 6 3 5 Input: 2 / \ 1 3 \ 4 sum = 5 Output: 1 4 2 3
Approach: Traverse the tree in pre-order manner from both the side, left and right and store the values of left and right side into the ArrayList LeftList and RightList respectively. On reaching the leaf node, take out the left side last value and right side last value from the respective ArrayLists. There will be three conditions:
- left side value + right side value < sum: Delete the last value of LeftList and make the left side execution to the right side because on moving from left side to the right side in the tree the value of node increases.
- left side value + right side value > sum: Delete the last value of RightList and make the right side execution to the left side because on moving from right side to the left side in the tree the value of node decreases.
- left side value + right side value = sum: Delete the last value of both the lists and make the left side execution to right side and right side execution to the left side.
Below is the implementation of the above approach:
1 7 2 6 3 5
- Find the maximum cost of an array of pairs choosing at most K pairs
- Find number of pairs (x, y) in an array such that x^y > y^x
- Find number of pairs in an array such that their XOR is 0
- Find k ordered pairs in array with minimum difference d
- Find the number of distinct pairs of vertices which have a distance of exactly k in a tree
- Pairs with Difference less than K
- Count pairs with given sum | Set 2
- Number of pairs whose sum is a power of 2
- Pairs such that one is a power multiple of other
- Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
- Swap Alternate Boundary Pairs
- Maximum Length Chain of Pairs | Set-2
- Count pairs in an array that hold i*arr[i] > j*arr[j]
- Maximizing Unique Pairs from two arrays
- No of pairs (a[j] >= a[i]) with k numbers in range (a[i], a[j]) that are divisible by x
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.
Improved By : princiraj1992