设计一个判别给定二叉树是否为二叉排序树的算法
时间: 2024-01-14 22:19:55 浏览: 129
以下是判断给定二叉树是否为二叉排序树的算法实现:
1.中序遍历法
```python
def is_bst(root):
def inorder(node):
nonlocal prev
if not node:
return True
if not inorder(node.left):
return False
if prev and prev.val >= node.val:
return False
prev = node
return inorder(node.right)
prev = None
return inorder(root)
```
2.递归法
```python
def is_bst(root):
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
val = node.val
if val <= lower or val >= upper:
return False
if not helper(node.right, val, upper):
return False
if not helper(node.left, lower, val):
return False
return True
return helper(root)
```
阅读全文