#include<iostream>
#include<string>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x);
};
Node::Node(int x) {
this->data = x;
this->left = NULL;
this->right = NULL;
}
class Tree {
Node* root;
public:
Tree();
~Tree();
void insert(int x);
void preorder(Node* node);
void inorder(Node* node);
void postorder(Node* node);
void show(string str);
void deltree(Node* node);
};
Tree::Tree() {
this->root = NULL;
}
Tree::~Tree() {
if (this->root) {
deltree(this->root);
}
}
void Tree::deltree(Node* node) {
if (node != NULL) {
deltree(node->left);
deltree(node->right);
delete node;
node = NULL;
}
}
void Tree::show(string str) {
if (str == "inorder") {
cout << "中序遍历开始\n";
inorder(this->root);
cout << "中序遍历结束\n";
}
if (str == "postorder") {
cout << "后序遍历开始\n";
postorder(this->root);
cout << "后序遍历结束\n";
}
if (str == "preorder") {
cout << "前序遍历开始\n";
preorder(this->root);
cout << "前序遍历结束\n";
}
}
void Tree::preorder(Node* node) {
if (node != NULL) {
cout << node->data << endl;
preorder(node->left);
preorder(node->right);
}
}
void Tree::inorder(Node* node) {
if (node != NULL) {
inorder(node->left);
cout << node->data << endl;
inorder(node->right);
}
}
void Tree::postorder(Node* node) {
if (node != NULL) {
postorder(node->left);
postorder(node->right);
cout << node->data << endl;
}
}
void Tree::insert(int x) {
Node* p = new Node(x);
if (this->root == NULL) {
this->root = p;
}
else {
Node* temp = this->root;
while (x < temp->data) {
if (temp->left == NULL) {
temp->left = p;
break;
}
temp = temp->left;
}
while (x >= temp->data) {
if (temp->right == NULL) {
temp->right = p;
break;
}
temp = temp->right;
}
}
}
int main() {
Tree tree;
int arr[] = { 2,5,7,-1,-9,-3,9 };
int length = 7;
for (int i = 0; i < length; i++) {
tree.insert(arr[i]);
}
tree.show("preorder");
tree.show("inorder");
tree.show("postorder");
return 0;
}
C++实现简单的二叉树例子
最新推荐文章于 2023-06-29 10:59:49 发布