C++实现简单的二叉树例子

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值