以二叉链表为二叉树的存储结构,设计一个算法判断一棵二叉树是否是正则二叉树。正则二叉树是指在二叉树中不存在度为1的结点。
时间: 2023-12-10 10:33:43 浏览: 105
以下是判断一棵二叉树是否是正则二叉树的Python算法:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 判断一棵二叉树是否是正则二叉树
def is_regular_binary_tree(root):
if not root:
return True
if not root.left and not root.right:
return True
if not root.left or not root.right:
return False
return is_regular_binary_tree(root.left) and is_regular_binary_tree(root.right)
# 测试代码
# 创建一棵正则二叉树
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)
root.right.right = TreeNode(7)
print(is_regular_binary_tree(root)) # 输出:True
# 创建一棵非正则二叉树
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)
print(is_regular_binary_tree(root)) # 输出:False
```
阅读全文