给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。用c++写
时间: 2024-06-13 12:07:51 浏览: 132
根据引用[1]和引用的思路,可以先根据给定的先序遍历序列和中序遍历序列构建出该二叉树,然后再计算该二叉树的高度。具体步骤如下:
1.定义二叉树节点结构体,包括节点值、左右子树指针。
```c++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
```
2.定义递归函数buildTree,根据给定的先序遍历序列和中序遍历序列构建二叉树。
```c++
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd) {
return NULL;
}
int rootVal = preorder[preStart];
int rootIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == rootVal) {
rootIndex = i;
break;
}
}
int leftSize = rootIndex - inStart;
TreeNode* root = new TreeNode(rootVal); root->left = buildTree(preorder, inorder, preStart + 1, preStart + leftSize, inStart, rootIndex - 1);
root->right = buildTree(preorder, inorder, preStart + leftSize + 1, preEnd, rootIndex + 1, inEnd);
return root;
}
```
3.定义递归函数getHeight,计算二叉树的高度。
```c++
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
```
4.在主函数中调用buildTree函数构建二叉树,再调用getHeight函数计算二叉树的高度。
```c++
int main() {
vector<int> preorder = {1, 2, 4, 5, 3, 6};
vector<int> inorder = {4, 2, 5, 1, 3, 6};
TreeNode* root = buildTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
int height = getHeight(root);
cout << "The height of the binary tree is: " << height << endl;
return 0;
}
```
阅读全文