一棵树中的最小值
Minimum in a Tree
我必须找到树中的最小数字。我写了这个,但它不起作用。我必须正确更改 运行 什么?我知道它不会占用树中的所有值。但是不知道改什么才行
public class MinTree {
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 int findMin(Tree tree){
int min = 99999;
Tree left, right;
if(min > tree.getVal())
min = tree.getVal();
System.out.println(min + " ");
if(tree.left() != null)
return findMin(tree.left());
if(tree.right() != null)
return findMin(tree.right());
return min;
}
public static void main(String[] args){
MinTree mt = new MinTree();
System.out.println("Minimum is :" + mt.findMin(tree));
}
}
树class:
class Tree {
public int obj;
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;
}
}
现在,它只会 return leftiest 树的最小值。
看,在函数 findMin(Tree tree)
中,您声明它必须 return findMin(tree.left())
的值,因为您没有将此值与 min
进行比较,只是 returning 它。
每当函数找到 return 代码时,它将 return 该值并完成该函数。所以,你应该做的是:
if(tree.left() != null){
int j = findMin(tree.left());
if (j<min){
min = j;
}
}
tree.right也是如此。这样,它将只取树的最小值。
此外,为什么要声明两棵未被使用的树?我的意思是 Tree left, right
,它没有任何作用,也没有使用 none。
另外,在System.out.println("Minimum is :" + mt.findMin(tree));
可能是系统不识别全局变量树。
我必须找到树中的最小数字。我写了这个,但它不起作用。我必须正确更改 运行 什么?我知道它不会占用树中的所有值。但是不知道改什么才行
public class MinTree {
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 int findMin(Tree tree){
int min = 99999;
Tree left, right;
if(min > tree.getVal())
min = tree.getVal();
System.out.println(min + " ");
if(tree.left() != null)
return findMin(tree.left());
if(tree.right() != null)
return findMin(tree.right());
return min;
}
public static void main(String[] args){
MinTree mt = new MinTree();
System.out.println("Minimum is :" + mt.findMin(tree));
}
}
树class:
class Tree {
public int obj;
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;
}
}
现在,它只会 return leftiest 树的最小值。
看,在函数 findMin(Tree tree)
中,您声明它必须 return findMin(tree.left())
的值,因为您没有将此值与 min
进行比较,只是 returning 它。
每当函数找到 return 代码时,它将 return 该值并完成该函数。所以,你应该做的是:
if(tree.left() != null){
int j = findMin(tree.left());
if (j<min){
min = j;
}
}
tree.right也是如此。这样,它将只取树的最小值。
此外,为什么要声明两棵未被使用的树?我的意思是 Tree left, right
,它没有任何作用,也没有使用 none。
另外,在System.out.println("Minimum is :" + mt.findMin(tree));
可能是系统不识别全局变量树。