写一段代码判断某一个二叉树是否为正则二叉树
时间: 2024-01-23 19:07:44 浏览: 72
好的,下面是 Python 代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_full_binary_tree(root: TreeNode) -> bool:
if not root:
return True
if not root.left and not root.right:
return True
if root.left and root.right:
return is_full_binary_tree(root.left) and is_full_binary_tree(root.right)
return False
def is_complete_binary_tree(root: TreeNode) -> bool:
if not root:
return True
queue = [root]
flag = False
while queue:
node = queue.pop(0)
if node.left:
if flag:
return False
queue.append(node.left)
else:
flag = True
if node.right:
if flag:
return False
queue.append(node.right)
else:
flag = True
return True
def is_perfect_binary_tree(root: TreeNode) -> bool:
depth = 0
node = root
while node.left:
depth += 1
node = node.left
return is_full_binary_tree(root) and is_complete_binary_tree(root, depth)
if __name__ == '__main__':
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_perfect_binary_tree(root)) # True
```
这段代码中,我们定义了三个函数:`is_full_binary_tree` 用于判断是否为满二叉树,`is_complete_binary_tree` 用于判断是否为完全二叉树,`is_perfect_binary_tree` 则用于判断是否为正则二叉树。
正则二叉树是一种特殊的二叉树,它既是满二叉树,又是完全二叉树。因此我们可以先判断是否为满二叉树,再判断是否为完全二叉树,如果两者都满足,则说明是正则二叉树。
阅读全文