I think the way to go is to use recursion on a custom tree structure.
The structure I'd use is one like the ones described here, but as a binary tree (with only two children). Example :
public class BinTree {
private float data;
private BinTree left; //left Sub-Tree
private BinTree right; //right Sub-Tree
/* creation of the tree */
public Tree(float rootData) {
data = rootData;
/* left and right are NULL, which means that
there is no left child and no right child */
}
public addLeft(float data) {
left = new BinTree(data);
/* You can verify first if there's a child,
and maybe give an exception if there is */
}
public addRight(T data) {
right = new BinTree(data);
/* You can verify first if there's a child,
and maybe give an exception if there is */
}
/* methods like your algorithm */
...
}
You can replace float
by any type
With this structure, recursion becomes quite easy.
And to deal with this problem recursively, you need to imagine this : you are at a node, what do you need to do on this node ? Do you need to apply something on the children ? If yes, how can you use the same function to have the expected output ?
From what I see of your picture, there is 3 cases :
1 - The value of the current node is So
Then, your child left should get the value So * u
and your child right should get the value So * d
.
2 - The value of the current node is So * nd
, for n
an integer
Then, your child left should get the value So * (n-1)d
(and just So
if n = 1
) and your child right should get the value So * (n+1)d
.
3 - The value of the current node is So * nu
, for n
an integer
Then, your child left should get the value So * (n+1)u
and your child right should get the value So * (n-1)u
.
So the implementation (of the method) should be like :
public myAlgo(float s /*So*/, T/*the type of your variable m*/ m, int height) {
myAlgo_rec(s, m, height, 0);
}
private myAlgo_rec(float s, T m, int height, int occurU) {
/* occurU is equivalent to n, and indicates if we use U or D depending on the sign */
if (height == 0) return; // Stop condition
if (occurU = 0) {
left = new BinTree(s * m.U);
right = new BinTree(s * m.D);
myAlgo_rec(s, m, height-1, 1);
myAlgo_rec(s, m, height-1, -1);
} else if (occurU < 0) {
left = new BinTree(s * Math.pow(m.U(), -occurU+1));
right = new BinTree(s * Math.pow(m.U(), -occurU-1));
myAlgo_rec(s, m, height-1, occurU+1);
myAlgo_rec(s, m, height-1, occurU-1);
} else /*occurU > 0*/ {
left = new BinTree(s * Math.pow(m.D(), occurU+1));
right = new BinTree(s * Math.pow(m.D(), occurU-1));
myAlgo_rec(s, m, height-1, occurU+1);
myAlgo_rec(s, m, height-1, occurU-1);
}
}
Here it is. Normally, I think that if you understood all I said, you should be able to implement it or use my code (and debug it).