(1)编程完成图1中二叉树的构造。 (2)编程实现图1中二叉树的先序、中序、后序的递归遍历。 (3)编程实现图1中二叉树的结点总数计算和叶子结点总数计算的算法实现 (4)编程实现图1中二叉树的高度计算的算法实现
时间: 2024-11-12 11:33:11 浏览: 19
PHP基于非递归算法实现先序、中序及后序遍历二叉树操作示例
首先,我们需要创建一个简单的二叉树节点结构,并根据需求分别实现:
```python
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
# 图1中的二叉树构造函数,示例:
def build_tree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
return root
# 先序遍历(根-左-右)
def pre_order_traversal(node):
if node is not None:
print(node.value)
pre_order_traversal(node.left)
pre_order_traversal(node.right)
# 中序遍历(左-根-右)
def in_order_traversal(node):
if node is not None:
in_order_traversal(node.left)
print(node.value)
in_order_traversal(node.right)
# 后序遍历(左-右-根)
def post_order_traversal(node):
if node is not None:
post_order_traversal(node.left)
post_order_traversal(node.right)
print(node.value)
# 计算结点总数
def count_nodes(node):
if node is None:
return 0
return 1 + count_nodes(node.left) + count_nodes(node.right)
# 计算叶子结点总数(没有子节点的结点)
def count_leaves(node):
if node is None or (node.left is None and node.right is None):
return 1
else:
return count_leaves(node.left) + count_leaves(node.right)
# 计算二叉树高度(最长路径的长度)
def height(node):
if node is None:
return 0
else:
left_height = height(node.left)
right_height = height(node.right)
return max(left_height, right_height) + 1
```
以上代码实现了二叉树的基本构建以及遍历、节点总数、叶子结点总数和高度的计算。你可以根据需要在实际项目中应用它们。如果有其他疑问,可以提问哦!
阅读全文