我需要在java中实现二叉树,其中右侧节点的值是用function1()计算的,它以父节点的父节点和父节点作为输入,左节点的值用function2()计算它将父节点作为输入。 (对于前两个子节点,父节点值的父节点和父节点是预先确定的) 节点填充其各自功能的返回值,直到其中一个节点具有程序正在查找的值。如果函数在某一点产生所需的值,我们需要打印到该节点的路径,即哪个函数顺序产生所需的值。如果使用给定的函数无法获得该值,那么我们打印出" false"
您能否告诉我实施此算法的最佳方法?
编辑:让我们假设: 1. function1是:
int function1(p_node.value, p_node.p_node.value)
{ `return 5*p_node.value+6*p_node.p_node.value;}
2:function2是:
int function2(p_node.value){
return 5*p_node;}
然后,
node.right_node.value=function1(node.p_node.value, node.p_node.pnode.value)
if(node.right_node.value==desired_output) "print path_to_the_node"
node.left_node.value=function2(node.p_node.value);
if(node.left_node.value==desired_output) "print path_to_the_node"
答案 0 :(得分:1)
Breadth-first search。这是一个示例:
void findPath(Node secondChildNode, int desiredOutput){
Node n = breadthFirstSearch(secondChildNode, desiredOutput);
if(n == null)
System.out.println("false");
else{
ArrayList<Node> list = new ArrayList<>();
while(n != null){
list.add(n);
n = n.pNode;
}
for(int i = list.size() - 1; i >= 0; i--)
System.out.println(list.get(i).value);
}
}
Node breadthFirstSearch(Node secondChildNode, int desiredOutput){
if(!secondChildNode.isPossible())
return null;
Queue<Node> q = new LinkedList<Node>();
q.add(secondChildNode);
Node t;
while((t = q.poll()) != null){
if(t.value == desiredOutput)
return t;
Node left = t.createLeftChild();
if(left.isPossible(desiredOutput))
q.add(left);
Node right = t.createRightChild();
if(right.isPossible(desiredOutput))
q.add(right);
}
return null;
}
您需要实施Node
,这是一项简单明了的工作。
class Node{
Node pNode;
int value;
Node(Node pNode, int value){/* ... */}
Node createLeftChild(){/* ... */}
Node createRightChild(){/* ... */}
boolean isPossible(int desiredOutput){
return value <= desiredOutput;
}
/* ...... */
}
现在,我看到了您对function1()
和function2()
的定义。如果desiredOutput
位于node
的子树中,则为node.value <= desiredOutput
。否则,它的子树的值越来越大,并且它的子树<= desiredOutput
的一天没有值。 (假设root的值为正)