我有 .h 文件和 .cpp 文件的代码。我只是不知道如何主要使用它。这是给定的,我需要写主要内容。
.h文件:
class binary_tree {
public:
class node;
binary_tree();
void addRoot(const std::string &data);
void addLeft(node *nd, const std::string &data);
void addRight(node *nd, const std::string &data);
node *getRoot();
std::string get(node *node);
bool isEmpty();
private:
node *root;
};
struct binary_tree::node {
node(const std::string &data);
std::string data;
node *left, *right;
};
这是我第一次使用二叉树,最让我困惑的是类中的类。我只需要知道如何将字符串添加到树中。
最佳答案
一些示例用法:
int main()
{
// construct the tree
binary_tree tree;
// add a root
tree.addRoot("this is the root");
// add children to the root
tree.addRight(tree.getRoot(), "left child");
tree.addRight(tree.getRoot(), "right child");
// get the data with either of these:
std::cout << tree.getRoot()->left->data;
std::cout << tree.get(tree.getRoot()->left);
return 0;
}
关于c++ - 如何使用这个二叉树类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368526/