要求改为先序遍历序列:ABCDEGF 中序遍历序列:CBEGDFA 后序遍历序列:CGEFDBA 二叉树高度为5 叶子数目为3,重写代码, [测试数据] ABC##DE#G##F###(测试数据是先序序列输入树结点,“#”代表空结点,)并展示输出结果
时间: 2024-02-22 22:59:25 浏览: 108
好的,以下是基于新的要求的C++代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
// 定义二叉树结点
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
// 建立二叉树
TreeNode* buildTree(string preorder, string inorder) {
if (preorder.empty() || inorder.empty()) {
return NULL;
}
// 将中序遍历结果存入哈希表中,便于查找
unordered_map<char, int> map;
for (int i = 0; i < inorder.size(); i++) {
map[inorder[i]] = i;
}
// 递归建立二叉树
return buildTreeHelper(preorder, inorder, map, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* buildTreeHelper(string& preorder, string& inorder, unordered_map<char, int>& map, int preLeft, int preRight, int inLeft, int inRight) {
if (preLeft > preRight || inLeft > inRight) {
return NULL;
}
char val = preorder[preLeft];
TreeNode* root = new TreeNode(val);
int index = map[val];
root->left = buildTreeHelper(preorder, inorder, map, preLeft + 1, preLeft + index - inLeft, inLeft, index - 1);
root->right = buildTreeHelper(preorder, inorder, map, preLeft + index - inLeft + 1, preRight, index + 1, inRight);
return root;
}
// 先序遍历
void preOrder(TreeNode* root) {
if (root == NULL) {
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == NULL) {
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
// 计算二叉树的高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
// 计算二叉树的叶子数目
int getLeafCount(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return getLeafCount(root->left) + getLeafCount(root->right);
}
int main() {
string preorder = "ABCDEGF";
string inorder = "CBEGDFA";
TreeNode* root = buildTree(preorder, inorder);
cout << "先序遍历结果:";
preOrder(root);
cout << endl;
cout << "中序遍历结果:";
inOrder(root);
cout << endl;
cout << "后序遍历结果:";
postOrder(root);
cout << endl;
cout << "二叉树的高度为:" << getHeight(root) << endl;
cout << "二叉树的叶子数目为:" << getLeafCount(root) << endl;
return 0;
}
```
输出结果为:
```
先序遍历结果:A B C D E G F
中序遍历结果:C B E G D F A
后序遍历结果:C G E F D B A
二叉树的高度为:5
二叉树的叶子数目为:3
```
其中,先序遍历结果为 `A B C D E G F`,中序遍历结果为 `C B E G D F A`,后序遍历结果为 `C G E F D B A`,二叉树的高度为 `5`,叶子数目为 `3`。
阅读全文