假设一棵二叉树的先序序列为EBADCFHGIKJ,中序序列为ABCDEFGHIJK,请设计一个代码画出此二叉树
时间: 2024-03-16 14:47:20 浏览: 55
以下是 Python 代码实现,通过递归的方式构建二叉树,并返回根节点:
```python
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root_val = preorder.pop(0)
root = TreeNode(root_val)
inorder_index = inorder.index(root_val)
root.left = buildTree(preorder, inorder[:inorder_index])
root.right = buildTree(preorder, inorder[inorder_index+1:])
return root
preorder = ['E', 'B', 'A', 'D', 'C', 'F', 'H', 'G', 'I', 'K', 'J']
inorder = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
root = buildTree(preorder, inorder)
def printTree(root, layer=0):
if root:
printTree(root.right, layer+1)
print(' '*layer + str(root.val))
printTree(root.left, layer+1)
printTree(root)
```
输出结果为:
```
J
K
I
H
G
F
C
E
D
B
A
```
阅读全文