在 Java 中实现的二叉搜索树 - 递归查找元素



使用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!");
    }
 }

我得到打印为"找不到元素"。

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

提前感谢!

递归版本:

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

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

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

我相信你的isFound = false;是总是得到回报的东西。

它应该是这样的:

isFound= findValueRecursively(currentNode.getLeftNode(), value);
    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。不过,您可以更改它以返回布尔值。

最新更新