以二叉链表作为二叉树的存储结构,设计以下算法。 (1)统计二叉树的叶结点个数。 (2)判别两棵树是否相等。 (3)交换二叉树每个结点的左孩子和右孩子。 (4)设计二叉树的双序遍历算法(双序遍历是指对于二叉树的每一个结点来说,先访问
时间: 2024-05-01 20:21:35 浏览: 105
该节点的左子树的最右下结点,再访问该节点本身,最后访问该节点的右子树的最左下结点。)
(1) 统计二叉树的叶结点个数算法:
```python
def count_leaf_node(root):
if not root:
return 0
if not root.left and not root.right:
return 1
return count_leaf_node(root.left) + count_leaf_node(root.right)
```
(2) 判别两棵树是否相等算法:
```python
def is_same_tree(p, q):
if not p and not q:
return True
elif not p or not q:
return False
elif p.val != q.val:
return False
else:
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
```
(3) 交换二叉树每个结点的左孩子和右孩子算法:
```python
def swap_left_right(root):
if not root:
return
root.left, root.right = root.right, root.left
swap_left_right(root.left)
swap_left_right(root.right)
```
(4) 设计二叉树的双序遍历算法:
```python
def double_order_traversal(root):
if not root:
return
if root.left:
node = root.left
while node.right:
node = node.right
print(node.val)
print(root.val)
if root.right:
node = root.right
while node.left:
node = node.left
print(node.val)
double_order_traversal(root.left)
double_order_traversal(root.right)
```
注意:这里的双序遍历是一种特殊的遍历方式,并不是二叉树的常规遍历方式。
阅读全文
相关推荐












