假设二叉树买用二叉链存储结构,二叉树中绪点值为单个字符且所有结点值不相同,设计二叉树的基本运節程序,包我的建一叉往,編出:二叉树。求二叉铺的商度,求緒点数和时子结点数;并用相关数据进行测试。
时间: 2023-12-22 11:03:03 浏览: 84
下面是二叉树的基本运算程序,包括建立二叉树、求二叉树深度、求二叉树结点数、求二叉树叶子结点数等。
```C++
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
};
// 建立二叉树
void createTree(TreeNode* &root) {
char ch;
cin >> ch;
if (ch == '#') {
root = nullptr;
} else {
root = new TreeNode(ch);
createTree(root->left);
createTree(root->right);
}
}
// 求二叉树深度
int getDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
// 求二叉树结点数
int getNodeCount(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftCount = getNodeCount(root->left);
int rightCount = getNodeCount(root->right);
return leftCount + rightCount + 1;
}
// 求二叉树叶子结点数
int getLeafCount(TreeNode* root) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
int leftCount = getLeafCount(root->left);
int rightCount = getLeafCount(root->right);
return leftCount + rightCount;
}
// 层次遍历二叉树
void levelTraversal(TreeNode* root) {
if (root == nullptr) {
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
cout << node->val << " ";
if (node->left != nullptr) {
q.push(node->left);
}
if (node->right != nullptr) {
q.push(node->right);
}
}
}
int main() {
TreeNode* root;
createTree(root);
cout << "二叉树深度:" << getDepth(root) << endl;
cout << "二叉树结点数:" << getNodeCount(root) << endl;
cout << "二叉树叶子结点数:" << getLeafCount(root) << endl;
cout << "层次遍历二叉树:";
levelTraversal(root);
cout << endl;
return 0;
}
```
测试数据:
```
输入:AB#C##D##
输出:
二叉树深度:3
二叉树结点数:4
二叉树叶子结点数:2
层次遍历二叉树:A B C D
```
阅读全文