gpt4 book ai didi

java - 我的递归程序没有按预期返回树中的最小元素

转载 作者:行者123 更新时间:2023-11-30 08:40:43 24 4
gpt4 key购买 nike

我有一棵树,我正在尝试编写一个递归方法来查找树中的最小值,但是我的方法没有返回树中的最小元素,我运行程序时的输出是 Minimum 是: 24。这是我的代码:

package weekFour;

public class MinTree {

static int min;

static Tree tree = new Tree( 24,
new Tree( 45,
null ,
new Tree(8, null , null) ) ,
new Tree ( 17,
new Tree (74 , null , null ) ,
null ) );

public static void main(String[] args){
MinTree mt = new MinTree();
System.out.println("Minimum is: " + mt.findMin(tree, Integer.MAX_VALUE));
}

public int findMin(Tree tree, int min){

if(tree.getVal() < min) {

min = tree.getVal();
}

Tree tree1 = tree.left();
if (tree1 != null) {
findMin(tree1, min);
}

Tree tree2 = tree.right();
if (tree2 != null) {
findMin(tree2, min);
}

return min;
}


}

class Tree {

private int val;
private Tree left, right;

public Tree(int val, Tree left, Tree right){
this.val = val;
this.left = left;
this.right = right;
}

public int getVal(){
return val;
}

public Tree left(){
return left;
}

public Tree right(){
return right;
}
}

谢谢你的时间

最佳答案

在您的 findMin 方法中,您没有捕获递归调用的结果...

改变:

Tree tree1 = tree.left();
if (tree1 != null) {
findMin(tree1, min);
}

Tree tree2 = tree.right();
if (tree2 != null) {
findMin(tree2, min);
}

像这样:

Tree tree1 = tree.left();
if (tree1 != null) {
min = findMin(tree1, min);
}

Tree tree2 = tree.right();
if (tree2 != null) {
min = findMin(tree2, min);
}

关于java - 我的递归程序没有按预期返回树中的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35512436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com