【发布时间】:2015-07-16 22:44:07
【问题描述】:
我必须在树中找到最小的数字。我写了这个,但它不起作用。我必须改变什么才能正常运行?我知道它不会占用树中的每个值。但我不知道要换什么工作。
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 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;
}
}
【问题讨论】:
-
如果右子树的结果低于左子树的结果会怎样?如果当前值低于两者会怎样?
-
您需要将
tree.getVal()与左右树的最小值进行比较,如果它们不为空,则返回这三个值中的最小值(最多)。如果它是非空的,你当前只是从左树返回值,如果它是非空的,则返回右树的值,否则返回当前节点的值。 -
好吧,我知道如何在每一边都做到最低限度,但我不知道如何将它们组合在一起。