C++代码要求:1、用模版类建立一个二叉树
时间: 2023-06-18 07:06:04 浏览: 96
以下是使用模板类建立二叉树的 C++ 代码:
```c++
template <typename T>
class BinaryTreeNode {
public:
BinaryTreeNode(T value) : m_value(value), m_left(nullptr), m_right(nullptr) {}
T value() const { return m_value; }
BinaryTreeNode* left() const { return m_left; }
BinaryTreeNode* right() const { return m_right; }
void setLeft(BinaryTreeNode* node) { m_left = node; }
void setRight(BinaryTreeNode* node) { m_right = node; }
private:
T m_value;
BinaryTreeNode* m_left;
BinaryTreeNode* m_right;
};
template <typename T>
class BinaryTree {
public:
BinaryTree() : m_root(nullptr) {}
void insert(T value) {
if (!m_root) {
m_root = new BinaryTreeNode<T>(value);
return;
}
BinaryTreeNode<T>* node = m_root;
while (true) {
if (value < node->value()) {
if (node->left()) {
node = node->left();
} else {
node->setLeft(new BinaryTreeNode<T>(value));
return;
}
} else {
if (node->right()) {
node = node->right();
} else {
node->setRight(new BinaryTreeNode<T>(value));
return;
}
}
}
}
BinaryTreeNode<T>* root() const { return m_root; }
private:
BinaryTreeNode<T>* m_root;
};
```
使用方法:
```c++
BinaryTree<int> tree;
tree.insert(5);
tree.insert(2);
tree.insert(8);
tree.insert(1);
tree.insert(3);
BinaryTreeNode<int>* root = tree.root();
// 遍历二叉树
```
阅读全文