为什么检查二叉树有效性的解决方案不起作用?

时间:2015-11-19 15:29:36

标签: java recursion binary-search-tree

我正在解决一个问题,以检查二叉树是否是有效的二叉树。这意味着某个节点左侧节点的值较小,右侧节点的值大于节点值。该程序使用递归方法执行检查并返回布尔值以确定树的有效性。我提供了以下代码,

class Node {

      Node left;
      Node right; 
       int data;

     public Node(int data_ ){

       this.data = data_;
   }
}

public class myTest{


private static List<Integer> lis = new ArrayList<Integer>();

public static List<Integer> inOrder(Node root){

    if (root != null){

        inOrder(root.left);

        lis.add(root.data);
        System.out.println( root.data );
        inOrder(root.right);
    }

    return lis;
}

public static boolean isBST( Node root, int min, int max  ){

    if (root ==  null )
        return true;

    return ( root.data >= min) 
        && ( root.data <= max ) 
        && isBST(root.left, min, root.data) 
        && isBST( root.right, root.data, max );
}

public static void main(String[] args){  

// form the bst
 Node root = new Node(5);
   root.left = new Node(3);
   root.right = new Node(7); 

   root.left.left = new Node(1);
   root.left.right = new Node(2);

   root.right.left = new Node(6);
   root.right.right = new Node(9);

   // get the max and min value from the tree
   int max = 0;
   int min  = 0;

   if (root != null ){

      List<Integer> li  = inOrder(root);
      min =  li.get(0);
      max = li.get( li.size() -1 );
   }


   // determine the validity 
   boolean bol_ = isBST(root, min, max );

   if ( bol_)
     System.out.println("valid BST ");

    else 
        System.out.println("Not valid BST ");
  }

  }

提供的测试树是有效的,但程序告诉它不是。我内心没有看到的问题是什么?此外,改善代码的优势是什么?说,我是否需要检查树内的所有值是否都是不同的整数以及如何做到这一点?

3 个答案:

答案 0 :(得分:1)

正如@Thomas指出的那样,你的树不是有效的BST。

但是我想给你一些建议。当您尝试评估树是否是二叉树或递归时,有很多边缘情况。一个更简单的解决方案是按顺序遍历树,将元素存储在ArrayList中,然后检查列表是否已排序。这种实现更容易/更简单,并且在相同的时间复杂度下运行但具有更大的空间复杂度:两者都是O(n)。

答案 1 :(得分:1)

因此:

root.left = new Node(3);
root.left.right = new Node(2);

- &GT;在右侧必须有高于根的价值 - 像这样

root.left = new Node(2);
root.left.right = new Node(3);

答案 2 :(得分:0)

我改变了方法很少,现在又如下,

public static boolean isBST( Node root, int min, int max  ){

    if (root ==  null )
        return true;

    return ( root.data > min) 
        && ( root.data < max ) 
        && isBST(root.left, min, root.data) 
        && isBST( root.right, root.data, max );
}

虽然呼叫如下,

boolean bol_ = isBST(root, min - 1 , max +1 );