二进制搜索树用Java实现 - 递归查找元素

时间:2013-09-21 15:48:41

标签: recursion find binary-search-tree

使用Java,是否可以编写递归方法来查找二叉搜索树中的元素?我说不,因为递归重新追溯的性质,除非我实施不正确?我一直在网上搜索,我能找到的只是一个迭代版本。这是我的方法:

public boolean findValueRecursively(BSTNode node, int value){
   boolean isFound = false;
   BSTNode currentNode = node;

   if (value == currentNode.getData()){
      isFound = true;
      return isFound;
   } else if (value < currentNode.getData()){
      findValueRecursively(currentNode.getLeftNode(), value);
   } else{
      findValueRecursively(currentNode.getRightNode(), value);
   }

  return isFound;
}

// Node data structure
public class BSTNode
{
    private BSTNode leftNode;
    private BSTNode rightNode;
    private int data;
    public BSTNode(int value, BSTNode left, BSTNode right){
       this.leftNode = left;
       this.rightNode = right;
       this.data = value;
    }
}



public static void main(String[] args){
    BST bst = new BST();
    // initialize the root node
    BSTNode bstNode = new BSTNode(4, null, null);
    bst.insert(bstNode, 2);
    bst.insert(bstNode, 5);
    bst.insert(bstNode, 6);
    bst.insert(bstNode, 1);
    bst.insert(bstNode, 3); 
    bst.insert(bstNode, 7);
    if (bst.findValueRecursively(bstNode, 7)){
        System.out.println("element is found! ");
    } else{
        System.out.println("element is not found!");
    }
 }

我得到的印刷品是“找不到元素”。

任何帮助/提示或建议,非常欢迎。

提前致谢!

4 个答案:

答案 0 :(得分:8)

递归版:

public boolean findValueRecursively(Node node, int value){
        if(node == null) return false;
        return 
                node.data == value ||
                findValueRecursively(leftNode, value) ||
                findValueRecursively(rightNode, value);
    }

答案 1 :(得分:2)

递归版本,返回对找到的节点的引用:

public BinaryNode find(BinaryNode node, int value) {
    // Finds the node that contains the value and returns a reference to the node.
    // Returns null if value does not exist in the tree.                
    if (node == null) return null;
    if (node.data == value) {
        return node;
    } else {
        BinaryNode left = find(node.leftChild, value);
        BinaryNode right = find(node.rightChild, value);
        if (left != null) {
            return left;
        }else {
            return right;
        }   
    }
}

答案 2 :(得分:0)

我相信你的isFound = false;是什么总是回来。

应该是这样的:

isFound= findValueRecursively(currentNode.getLeftNode(), value);

答案 3 :(得分:0)

    public TreeNode<E> binarySearchTree(TreeNode<E> node, E data){
    if(node != null) {
        int side = node.getData().compareTo(data);
        if(side == 0) return node;
        else if(side < 0) return binarySearchTree(node.getRightChild(), data);
        else if(side > 0 ) return binarySearchTree(node.getLeftChild(), data);
    }

    return null;
}

这将返回对节点的引用,这是一个更有用的IRL。您可以将其更改为返回布尔值。

相关问题