簡體   English   中英

使用遞歸的 C++ 二叉搜索樹

[英]C++ Binary Search Tree using Recursion

嗨,有人可以向我解釋為什么以下內容不允許我使用 root.getLeft() 作為遞歸的參數嗎? 根據我的理解,將 root.getLeft() 作為參數傳遞給我的二叉搜索樹應該有效嗎?

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

我收到的問題消息是:消息:'沒有合適的構造函數可以將“節點 *”轉換為“節點”'

這是因為

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

需要一個const Node&但是

Node* Node::getLeft() const;

提供一個Node*

你的contains需要一個Node&而你給它一個Node* 您可以通過getLeftgetLeftgetRight獲得的指針來解決這個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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM