I want to find a path from the root of a binary search tree, whether it can generate a specific number by adding or multiplying nodes.
In another word, I want to show all numbers, which can generate by adding * or + between nodes of a path.
Note that the path should starts from the root to a leaf.
For example:
tree nodes: 10, 8, 3
number can produce from this path:
240 => 10 * 8 * 3
110 => 10 * (8 + 3)
21 => 10 + 8 + 3
83 => (10 * 8) + 3
54 => (10 + 8) * 3
34 => 10 + (8 * 3)
I wrote this code, which doesn't include parentheses.
private void findThePath(TreeNode tnode, int result, int n, List paths) {
// if node is null, return
if (tnode == null)
return;
//adding nodes to this list, in order to save the path
paths.add(tnode);
// if node is leaf node, and its data equals
// to user input, its path highlighted
if (tnode.leftCircle == null && tnode.rightCircle == null) {
if (result == n) {
paths.forEach(t -> t.highlightFlag = true);
paths.forEach(t -> System.out.print(t.rootCircle.getSearchKey() + " "));
}
}
// if left child exists, check for leaf,
// and insert * or + sign between nodes,
// recursively
if (tnode.leftCircle != null) {
findThePath(tnode.leftCircle, result + tnode.leftCircle.rootCircle.getSearchKey(), n, paths);
findThePath(tnode.leftCircle, result * tnode.leftCircle.rootCircle.getSearchKey(), n, paths);
}
// if right child exists, check for leaf
// and insert * or + sign between nodes,
// recursively
if (tnode.rightCircle != null) {
findThePath(tnode.rightCircle, result + tnode.rightCircle.rootCircle.getSearchKey(), n, paths);
findThePath(tnode.rightCircle, result * tnode.rightCircle.rootCircle.getSearchKey(), n, paths);
}
//we need to remove the last node in list because
//its not in left or right of the nodes
paths.remove(paths.size() - 1);
}
which it doesn't contain 8 * (5 + 3) and 8 + (5 * 3).