【问题标题】:Minimum in a Tree树中的最小值
【发布时间】: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() 与左右树的最小值进行比较,如果它们不为空,则返回这三个值中的最小值(最多)。如果它是非空的,你当前只是从左树返回值,如果它是非空的,则返回右树的值,否则返回当前节点的值。
  • 好吧,我知道如何在每一边都做到最低限度,但我不知道如何将它们组合在一起。

标签: java tree minimum


【解决方案1】:

现在,它只会返回 leftiest 树的最小值。

看,在函数findMin(Tree tree) 中,您声明它必须返回findMin(tree.left()) 的值,因为您没有将此值与min 进行比较,只是返回它。

只要函数找到返回码,它就会返回该值并完成函数。所以,你应该这样做:

if(tree.left() != null){
  int j = findMin(tree.left());
  if (j<min){
      min = j;
  }
}

tree.right 也是如此。这样,它将只取树的最小值。

另外,你为什么要声明两棵没有被使用的树?我的意思是Tree left, right,它什么也没做,也没有被使用。

另外,System.out.println("Minimum is :" + mt.findMin(tree)); 可能是系统无法识别全局变量树。

【讨论】:

  • 我尝试了不同的方法,但没有删除无用的代码 :D 。感谢您的帮助。
猜你喜欢
  • 2018-09-25
  • 2021-12-19
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多