#include <iostream>
#include <vector>
https://gitee.com/tongchaowei/front-native-page-template/tree/main/image-display/template-01
using namespace std;
class BinaryTree {
private:
vector<char> tree; // 存储二叉树的数组
int size; // 二叉树的结点数
// 计算索引i的左孩子和右孩子索引
pair<int, int> getChildren(int i) {
return {2 * i + 1, 2 * i + 2};
}
// 计算索引i的双亲索引
int getParent(int i) {
return (i - 1) / 2;
}
public:
BinaryTree() : size(0) {}
// 插入结点
void insert(char data) {
tree.push_back(data);
size++;
}
// 层序输出每个结点的双亲和孩子信息
void printParentChild() {
for (int i = 0; i < size; ++i) {
char parent = getParent(i) >= 0 ? tree[getParent(i)] : '无';
pair<int, int> children = getChildren(i);
char leftChild = children.first < size ? tree[children.first] : '无';
char rightChild = children.second < size ? tree[children.second] : '无';
cout << tree[i] << "结点的双亲是" << parent << ",左孩子是" << leftChild << ",右孩子是" << rightChild << endl;
}
}
// 前序遍历
void preOrder(int index = 0) {
if (index < size) {
cout << tree[index] << " ";
preOrder(getChildren(index).first);
preOrder(getChildren(index).second);
}
}
// 中序遍历
void inOrder(int index = 0) {
if (index < size) {
inOrder(getChildren(index).first);
cout << tree[index] << " ";
inOrder(getChildren(index).second);
}
}
// 后序遍历
void postOrder(int index = 0) {
if (index < size) {
postOrder(getChildren(index).first);
postOrder(getChildren(index).second);
cout << tree[index] << " ";
}
}
// 统计叶子结点数量,并输出每个叶子结点
void countAndPrintLeaves() {
int count = 0;
for (int i = 0; i < size; ++i) {
if (getChildren(i).first >= size && getChildren(i).second >= size) {
cout << tree[i] << " ";
count++;
}
}
cout << endl << "叶子结点数量:" << count << endl;
}
};
int main() {
BinaryTree bt;
// 假设输入的二叉树结点为:A B C D E F G H
char nodes[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
for (char node : nodes) {
bt.insert(node);
}
cout << "层序输出每个结点的双亲和孩子信息:" << endl;
bt.printParentChild();
cout << "前序遍历:" << endl;
bt.preOrder();
cout << endl;
cout << "中序遍历:" << endl;
bt.inOrder();
cout << endl;
cout << "后序遍历:" << endl;
bt.postOrder();
cout << endl;
cout << "统计叶子结点数量,并输出每个叶子结点:" << endl;
bt.countAndPrintLeaves();
return 0;
}