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 a pre-order manner from both the side, left and right, and store the values of the left and right sides into the ArrayList LeftList and RightList respectively. On reaching the leaf node, take out the left side last value and a 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 the 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 the 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 the right side and right side execution to the left side.
Below is the implementation of the above approach:
1 7 2 6 3 5
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live