根据二叉树的中序遍历和后序遍历创建 一棵二叉树,并且返回所创建的树的树高,具体方法请参见下面源码(经过调试,无任何bug存在)

本文介绍了一种根据中序遍历和后序遍历序列构建二叉树的方法,并提供了一个C++实现示例。此外,还展示了如何计算生成的二叉树的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;
class Node {
public:
char ch;
Node*left;
Node *right;
Node(char c, Node *lc, Node *rc) {
ch = c;
left = lc;
right = rc;
}
Node() {
}
~Node() {
delete left;
delete right;
}
};
//create a tree refer to the inorder and postorder
Node*create(char *inorder, char *postorder, int length) {
if (length == 0) {
return NULL;
} else {
Node *node = new Node;
node->ch = postorder[length - 1];
int rootIndex = 0;
for (; rootIndex < length; rootIndex++) {
if (inorder[rootIndex] == postorder[length - 1]) {
break;
}
}
node->left = create(inorder, postorder, rootIndex);
node->right = create(rootIndex + inorder + 1, postorder + rootIndex,
length - rootIndex - 1);
return node;
}
}
//return the height of a binary tree
int getHeight(Node *root) {
if (root == NULL) {
return 0;
} else
return 1 + max(getHeight(root->left), getHeight(root->right));
}
int main() {
char inorder[27];
char postorder[27];
int count;
Node *root;
int length;
cin >> count;
while (count > 0) {
cin >> inorder;
cin >> postorder;
length = strlen(postorder);
cout << "Start creating..." << endl;
cout << "The height of the tree is : "
<< getHeight(create(inorder, postorder, length)) << endl;
count--;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值