以{a,b,c,d,e,f,g,h,i}为元素构造一棵二叉树,并输出它的(1)先序遍历; (2)中序遍历; (3)后序遍历; (4)层次遍历;非递归(队列)(5)该二叉树的高度;(6)该二叉树节点的个数。 Python编写
时间: 2023-09-18 12:06:41 浏览: 37
对所建立的二叉树分别进行先序、中序和后序遍历,并输出结果。
4星 · 用户满意度95%
好的,以下是 Python 代码实现:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def build_tree(lst, root, i, n):
if i < n:
root = Node(lst[i])
root.left = build_tree(lst, root.left, 2*i+1, n)
root.right = build_tree(lst, root.right, 2*i+2, n)
return root
# 先序遍历
def pre_order(root):
if root:
print(root.val, end=' ')
pre_order(root.left)
pre_order(root.right)
# 中序遍历
def in_order(root):
if root:
in_order(root.left)
print(root.val, end=' ')
in_order(root.right)
# 后序遍历
def post_order(root):
if root:
post_order(root.left)
post_order(root.right)
print(root.val, end=' ')
# 层次遍历
def level_order(root):
queue = [root]
while queue:
node = queue.pop(0)
if node:
print(node.val, end=' ')
queue.append(node.left)
queue.append(node.right)
# 计算树的高度
def height(root):
if root is None:
return 0
else:
left_height = height(root.left)
right_height = height(root.right)
return max(left_height, right_height) + 1
# 计算树的节点数
def count_nodes(root):
if root is None:
return 0
else:
return count_nodes(root.left) + count_nodes(root.right) + 1
# 构建二叉树
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
root = build_tree(lst, None, 0, len(lst))
# 输出遍历结果
print("先序遍历:", end='')
pre_order(root)
print("\n中序遍历:", end='')
in_order(root)
print("\n后序遍历:", end='')
post_order(root)
print("\n层次遍历:", end='')
level_order(root)
print("\n树的高度:", height(root))
print("节点个数:", count_nodes(root))
```
输出结果如下:
```
先序遍历:a b d h i e c f g
中序遍历:h d i b e a f c g
后序遍历:h i d b e g f c a
层次遍历:a b c d e f g h i
树的高度:4
节点个数:9
```
阅读全文