以二叉链表作为二叉树的存储结构,编写以下算法: 1.统计二叉树的叶结点个数。 2.判别两棵树是否相等。 3.交换二叉树每个结点的左孩子和右孩子。 4.设计二叉树的双序遍历算法。
时间: 2024-05-11 08:18:56 浏览: 59
1. 统计二叉树的叶结点个数
```python
def count_leaf_nodes(root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
return count_leaf_nodes(root.left) + count_leaf_nodes(root.right)
```
2. 判别两棵树是否相等
```python
def is_same_tree(p, q):
if p is None and q is None:
return True
if p is None or q is None:
return False
if p.val != q.val:
return False
return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
```
3. 交换二叉树每个结点的左孩子和右孩子
```python
def invert_tree(root):
if root is None:
return
root.left, root.right = root.right, root.left
invert_tree(root.left)
invert_tree(root.right)
```
4. 设计二叉树的双序遍历算法
```python
def double_order_traversal(root):
if root is None:
return
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res_reversed = []
for i in range(len(res)-1, -1, -1):
res_reversed.append(res[i])
return res + res_reversed
```
阅读全文