在使用模板和unique_ptr实现的二叉搜索树中返回具有最小值的节点

时间:2014-07-06 02:49:04

标签: c++ c++11 binary-search-tree unique-ptr

我正在尝试使用unique_ptr实施BST。我想在BST中返回具有最小值的节点。我知道如何返回最小值并且我为它编写了函数但是如果我想返回节点怎么办?我可以上课吗?

#include <iostream>
#include <memory>

template<class T>
class BinarySearchTree{
    struct TreeNode;
    typedef std::unique_ptr<TreeNode> spTreeNode;
    struct TreeNode{
        T data;
        spTreeNode  left;
        spTreeNode  right;
        TreeNode(const T & value):data(value),left(nullptr),right(nullptr){}
    };



    spTreeNode root;
    bool insert(spTreeNode &node);
    void print(const spTreeNode&) const ;
public:
    BinarySearchTree();
    void insert( const T & node);
    void print()const;
    T getMin();

};

template<class T>
BinarySearchTree<T>::BinarySearchTree():root(nullptr){}

template<class T>
void BinarySearchTree<T>::insert(const T & ref)
{
    std::unique_ptr<TreeNode> node(new TreeNode(ref));
    if (root == nullptr) {
        root = std::move(node);
    } else {
        TreeNode* temp = root.get();
        TreeNode* prev = root.get();
        while (temp != nullptr) {
            prev = temp;
            if (temp->data < ref)
                temp = temp->right.get();
            else
                temp = temp->left.get();
        }
        if (prev->data < ref)
            prev->right = std::move(node);
        else
            prev->left = std::move(node);
    }
}


template<class T>
T BinarySearchTree<T>::getMin()
{
    TreeNode* temp = root.get();
    TreeNode *prev = nullptr;
    while (temp)
    {
        prev = temp;
        temp = temp->left.get();
    }
    return prev->data;
}


int main()
{
    BinarySearchTree<int> bst;
    bst.insert(13);
    bst.insert(3);
    bst.insert(5);
    bst.insert(31);
    bst.insert(511);
    bst.insert(311);
    std::cout << bst.getMin(); // Works but what if I want to return the Node?
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您必须决定所需的界面。是否要将const指针返回到现有的TreeNode?对TreeNode的const引用? TreeNode的副本?关键是要考虑引用/指针的有效期。

我坦率地认为这些都不是公共界面的好主意。因此,假设您将getMinNode()设为私有,并保持getMin()公开:

// Returns non-owning pointer; do not attempt to delete TreeNode.
template<class T>
const BinarySearchTree<T>::TreeNode* BinarySearchTree<T>::getMinNode() const
{
    // Like getMin(), but return prev
    // Does this work for empty BinarySearchTree?
    TreeNode* temp = root.get();
    TreeNode *prev = nullptr;
    while (temp)
    {
        prev = temp;
        temp = temp->left.get();
    }
    return prev;
}

template<class T>
T BinarySearchTree<T>::getMin() const   // member function is const
{
    return getMinNode()->data;
}