给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。并生成代码
时间: 2024-04-29 10:21:43 浏览: 95
以下是给定先序遍历序列和中序遍历序列计算二叉树高度的代码实现。
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, inorder):
if not inorder:
return None
root_val = preorder.pop(0)
root = TreeNode(root_val)
index = inorder.index(root_val)
root.left = buildTree(preorder, inorder[:index])
root.right = buildTree(preorder, inorder[index+1:])
return root
def getHeight(root):
if not root:
return 0
left_height = getHeight(root.left)
right_height = getHeight(root.right)
return max(left_height, right_height) + 1
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
root = buildTree(preorder, inorder)
print(getHeight(root))
```
输出结果为:
```
3
```
说明该二叉树的高度为 3。
阅读全文