提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
代码与注释如下
#include <iostream>
#include <queue>
using namespace std;
// 二叉树类型
struct BTNode {
int data;
BTNode *left, *right;
};
// 创建二叉树
BTNode* CreatBTtree(int* a, int n) {
BTNode* root = new BTNode();
root->data = a[0];
root->left = nullptr;
root->right = nullptr;
for (int i = 1; i < n; i++) {
BTNode* p = new BTNode();
p->data = a[i];
p->left = p->right = nullptr;
BTNode* c = root;
BTNode* pa;
while (c) {
pa = c;
if (p->data < c->data)
c = c->left;
else
c = c->right;
}
if (p->data < pa->data)
pa->left = p;
else
pa->right = p;
}
return root;
}
// 前序、中序和后序遍历
void priorder(BTNode* root) {
if (root) {
cout << root->data << " ";
priorder(root->left);
priorder(root->right);
}
}
void midorder(BTNode* root) {
if (root) {
priorder(root->left);
cout << root->data << " ";
priorder(root->right);
}
}
void posorder(BTNode* root) {
if (root) {
priorder(root->left);
priorder(root->right);
cout << root->data << " ";
}
}
//计算二叉树叶子节点数
int CountLeafNode(BTNode* root) {
int leaf = 0;
if (root) {
leaf += CountLeafNode(root->left);
leaf += CountLeafNode(root->right);
if (!leaf)
leaf = 1;
return leaf;
} else {
return 0;
}
}
//返回二叉树的层数
int Countfloors(BTNode* root) {
int floor = 0;
if (root)
floor = 1 + max(Countfloors(root->left), Countfloors(root->right));
return floor;
}
//查找key值的地址
BTNode* FindNode(BTNode* root, int key) {
if (root) {
if (key < root->data)
return FindNode(root->left, key);
else if (key > root->data)
return FindNode(root->right, key);
return root;
}
return nullptr;
}
//复制一棵二叉树
BTNode* BTcopy(BTNode* root) {
if (root) {
BTNode* croot = new BTNode();
croot->data = root->data;
croot->left = BTcopy(root->left);
croot->right = BTcopy(root->right);
return croot;
}
return nullptr;
}
//按层遍历
void levelorder(BTNode* root) {
queue<BTNode*> tmp;
vector<int> datasave;
tmp.push(root);
while (!tmp.empty()) {
if (tmp.front()->left)
tmp.push(tmp.front()->left);
if (tmp.front()->right)
tmp.push(tmp.front()->right);
datasave.push_back(tmp.front()->data);
tmp.pop();
}
for (int i = 0; i < datasave.size(); i++)
cout << datasave[i] << " ";
cout << endl;
}
//镜像二叉树
BTNode* MirrorTree(BTNode* root) {
while (root) {
BTNode* mroot = new BTNode();
mroot->data = root->data;
mroot->left = MirrorTree(root->right);
mroot->right = MirrorTree(root->left);
return mroot;
}
return nullptr;
}
int main() {
int a[] = {6, 2, 8, 1, 4, 10, 3, 5, 9};
int N = sizeof(a) / sizeof(int);
BTNode* tree = CreatBTtree(a, N);
priorder(tree);
cout << endl;
midorder(tree);
cout << endl;
posorder(tree);
cout << endl;
cout << "叶子节点数为: " << CountLeafNode(tree) << endl;
cout << "二叉树层数为: " << Countfloors(tree) << endl;
cout << "KEY的地址为: " << FindNode(tree, 5) << endl;
BTNode* tree2 = BTcopy(tree);
cout << "复制二叉树: ";
priorder(tree2);
cout << endl;
cout << "按层遍历为: ";
levelorder(tree);
BTNode* tree3 = MirrorTree(tree);
cout << "镜像二叉树: ";
priorder(tree3);
cout << endl;
return 0;
}