I need to search any combination of numbers in the BinaryTree that will give me the sum I am searching for. For example, for the tree that have the numbers: 9,1,6,3,2,5 if the system will receive the sum of 18, it will return the string "9,1,3,5". How can I do that please.
The combination need to start from the root and down in Pathway & the method need to work in BackTracking recursion
the code that I wrote is:
public String path(int sum)
{
return path(sum, root);
}
private String path(int sum, Node t)
{
if (t == null)
return "";
sum = sum - t.getNumber();
if (sum == 0)
return t.getNumber() + ", ";
return path(sum, t.getLeftSon()) + path(sum, t.getRightSon());
}
Your recursive implementation is really close to what you need, but there are a few things that need some adjusting.
First, a recursive implementation requires two things to work:
You run into the problem that you are only printing the final node that makes your sum evaluate to zero, as you recurse out. This is because the last call will then recurse back to the method that called it, where the sum is higher than zero .
if that tree reaches a leaf and the sum was not found, then it doesn't exist in that sub-tree.
return "";
else if the sum is found in the sub-tree.
return t.getNumber() + ", ";
else we haven't reached the sum, and there are more children nodes.
path(t.getleftSon()); path(t.getRightSon()); return t.getNumber() + ", "
I haven't tested this exact code in an IDE, but the logic should be correct
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.