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

时间:2016-02-19 18:32:40

标签: java recursion tree

我有一棵树,我正在尝试编写一个递归方法来查找树中的最小值但是我的方法没有返回树中的最小元素,我运行程序时的输出是Minimum is: 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;
   }
}

感谢您的时间

2 个答案:

答案 0 :(得分:2)

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);
}

答案 1 :(得分:0)

您是本地min name =静态变量的min名称。

更改它以获得正确的结果。或做这样的事情=&gt;

public int findMin(Tree tree, int min){

            if(tree.getVal() < min) {

                MinTree.min = tree.getVal();
            }

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

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

            return help.min;
        }