用C++ 编写一个程序,实现二叉树的下列运算: 输入一个二叉树的先序序列,生成二叉树的二叉链表; 显示其先序、中序和后序遍历结果; 计算二叉树的叶子结点数; 求二叉树的深度 。
时间: 2023-12-01 07:08:21 浏览: 72
二叉树操作合集 相关文章:https://blog.csdn.net/weixin_42708321/article/deta
5星 · 资源好评率100%
好的,我可以为您提供一个C++程序来实现这些操作。下面是代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BinaryTree {
public:
TreeNode* build_tree(vector<char>& preorder) {
if (preorder.empty()) {
return NULL;
}
char root_val = preorder[0];
preorder.erase(preorder.begin());
if (root_val == '#') {
return NULL;
}
TreeNode* root = new TreeNode(root_val - '0');
root->left = build_tree(preorder);
root->right = build_tree(preorder);
return root;
}
vector<int> preorder(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
res.push_back(root->val);
vector<int> left = preorder(root->left);
vector<int> right = preorder(root->right);
res.insert(res.end(), left.begin(), left.end());
res.insert(res.end(), right.begin(), right.end());
return res;
}
vector<int> inorder(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
vector<int> left = inorder(root->left);
res.insert(res.end(), left.begin(), left.end());
res.push_back(root->val);
vector<int> right = inorder(root->right);
res.insert(res.end(), right.begin(), right.end());
return res;
}
vector<int> postorder(TreeNode* root) {
vector<int> res;
if (!root) {
return res;
}
vector<int> left = postorder(root->left);
vector<int> right = postorder(root->right);
res.insert(res.end(), left.begin(), left.end());
res.insert(res.end(), right.begin(), right.end());
res.push_back(root->val);
return res;
}
int count_leaves(TreeNode* root) {
if (!root) {
return 0;
}
if (!root->left && !root->right) {
return 1;
}
return count_leaves(root->left) + count_leaves(root->right);
}
int depth(TreeNode* root) {
if (!root) {
return 0;
}
int left_depth = depth(root->left);
int right_depth = depth(root->right);
return max(left_depth, right_depth) + 1;
}
};
int main() {
string preorder_str;
cin >> preorder_str;
vector<char> preorder(preorder_str.begin(), preorder_str.end());
BinaryTree tree;
TreeNode* root = tree.build_tree(preorder);
cout << "先序遍历结果:";
vector<int> res = tree.preorder(root);
for (int i = 0; i < res.size(); i++) {
cout << " " << res[i];
}
cout << endl;
cout << "中序遍历结果:";
res = tree.inorder(root);
for (int i = 0; i < res.size(); i++) {
cout << " " << res[i];
}
cout << endl;
cout << "后序遍历结果:";
res = tree.postorder(root);
for (int i = 0; i < res.size(); i++) {
cout << " " << res[i];
}
cout << endl;
cout << "叶子结点数:" << tree.count_leaves(root) << endl;
cout << "二叉树深度:" << tree.depth(root) << endl;
return 0;
}
```
您可以将上述代码保存为一个.cpp文件,在终端中运行该文件,然后输入二叉树的先序遍历序列,程序将会输出先序、中序、后序遍历结果,叶子结点数和二叉树深度。
阅读全文