c++二叉树
时间: 2023-07-01 21:20:05 浏览: 76
C++ 二叉树
好的,下面是一个简单的 C++ 二叉树的实现:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BinaryTree {
private:
TreeNode* root;
public:
BinaryTree() {
root = NULL;
}
void insert(int val) {
TreeNode* newNode = new TreeNode(val);
if (root == NULL) {
root = newNode;
return;
}
TreeNode* curr = root;
while (true) {
if (val < curr->val) {
if (curr->left == NULL) {
curr->left = newNode;
return;
}
curr = curr->left;
} else {
if (curr->right == NULL) {
curr->right = newNode;
return;
}
curr = curr->right;
}
}
}
void inorderTraversal(TreeNode* node) {
if (node == NULL) {
return;
}
inorderTraversal(node->left);
cout << node->val << " ";
inorderTraversal(node->right);
}
void inorderTraversal() {
inorderTraversal(root);
}
void preorderTraversal(TreeNode* node) {
if (node == NULL) {
return;
}
cout << node->val << " ";
preorderTraversal(node->left);
preorderTraversal(node->right);
}
void preorderTraversal() {
preorderTraversal(root);
}
void postorderTraversal(TreeNode* node) {
if (node == NULL) {
return;
}
postorderTraversal(node->left);
postorderTraversal(node->right);
cout << node->val << " ";
}
void postorderTraversal() {
postorderTraversal(root);
}
};
int main() {
BinaryTree tree;
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(9);
cout << "Inorder Traversal: ";
tree.inorderTraversal();
cout << endl;
cout << "Preorder Traversal: ";
tree.preorderTraversal();
cout << endl;
cout << "Postorder Traversal: ";
tree.postorderTraversal();
cout << endl;
return 0;
}
```
这个二叉树实现了插入节点、中序遍历、前序遍历和后序遍历等基本操作。你可以根据需要进行修改和扩展。
阅读全文