这是我的FibonacciTree生成类: 它有生成Fibonacci函数结果的二叉树和Fibonacci参数树的方法。 但我无法实现生成调用序列树的方法,例如:
package dynamicdata;
public class FiboTree {
int value;
FiboTree left;
FiboTree right;
FiboTree(int value, FiboTree left, FiboTree right) {
this.value = value;
this.left = left;
this.right = right;
}
static int getFiboVal(int val) {
return (val > 2) ? getFiboVal(val - 1) + getFiboVal(val - 2) : 1;
}
static FiboTree generateArg(int val) {
return (val > 1) ? new FiboTree(val, generateArg(val - 2), generateArg(val - 1)) : new FiboTree(val, null, null);
}
static FiboTree generateVal(int val){
return (val > 2) ? new FiboTree(getFiboVal(val), generateVal(val - 2), generateVal(val - 1)) : new FiboTree(1, null, null);
}
static void print(FiboTree root, int depth) {
if(root != null) {
print(root.right, depth + 1);
for(int k = 0; k < depth; k++) {
System.out.print(" ");
}
System.out.println(root.value + "[");
print(root.left, depth + 1);
}
}
@Override
public String toString(){
return getTreeToString(this);
}
String getTreeToString(FiboTree node){
return (node != null) ? "[root: " + node.value + " left: " + getTreeToString(node.left) + " right: " + getTreeToString(node.right)
+ "]": "";
}
int getSize(FiboTree node) {
return (node != null) ? 1 + getSize(node.left) + getSize(node.right) : 0;
}
static FiboTree generateNum(int val) {
return genNumCount(val, val);
}
static FiboTree genNumCount(int val, int cnt) {
}
public static void main(String[] args) {
FiboTree tree = generateNum(5);
tree.print(tree, 0);
}
}
提前感谢任何解决方案! * P.S。我应该实现的方法 - “generateNum”
答案 0 :(得分:0)
我在这项任务中有晋升机会:
static FibTree generateNum(int val) {
return genNumCount(val, val);
}
static FibTree genNumCount(int val, int nls) {
if (val > 1) {
FibTree rec = new FibTree(nls + 1, genNumCount(val - 1, nls + 1), new FibTree(val, null, null)); //genNumCount(val - 1, nls)
return rec;
} else {
return new FibTree(val, null, null);
}
}
public static void main(String[] args) {
FibTree tree = generateNum(4);
print(tree, 0);
}
树计数器以正确的方式工作,但仍然不够。 需要改进rec.right参考。 有人可以帮忙吗?