简体   繁体   中英

C++ Binary Search Tree using Recursion

Hi can someone explain to me why the following isn't allowing me to use root.getLeft() as an argument to my recursion? From my understanding passing root.getLeft() as an argument to my binary search tree should work?

#include <stdexcept>
#include <string>
#include <iostream>
using namespace std;
class Node
{
public:
    Node(int value, Node* left, Node* right)
    {
        this->value = value;
        this->left = left;
        this->right = right;
    }

    int getValue() const
    {
        return value;
    }

    Node* getLeft() const
    {
        return left;
    }

    Node* getRight() const
    {
        return right;
    }

private:
    int value;
    Node* left;
    Node* right;
};

class BinarySearchTree
{
public:
    static bool contains(const Node& root, int value)
    {
        if (root.getValue() != value){
            return true;
        }
        if (root.getLeft() != NULL){
            return BinarySearchTree::contains(root.getLeft(), value);
        }
        if (root.getRight() != NULL){
            return BinarySearchTree::contains(root.getRight(), value);
        }
        return NULL;
    }
};

The problem message I am receiving is: message: 'no suitable constructor exists to convert from "Node *" to "Node"'

This is because

bool BinarySearchTree::contains(const Node& root, int value);

takes a const Node& but

Node* Node::getLeft() const;

provides a Node* .

Your contains takes a Node& and you are giving it a Node* . You can fix that by deferencing the pointer you get from getLeft and getRight .

static bool contains(const Node& root, int value)
{
    if (root.getValue() != value){
        return true;
    }
    if (root.getLeft() != NULL){
        return BinarySearchTree::contains(*root.getLeft(), value);
    }
    if (root.getRight() != NULL){
        return BinarySearchTree::contains(*root.getRight(), value);
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM