!/usr/bin/env python3
lass TreeNode:
"""
二叉树基类, 双向链表, 用于存储二叉树数据
"""
def __init__(self, val, left_node=None, right_node=None):
# 父节点值
self.val = val
# 左子树
self.left = left_node
# 右子树
self.right = right_node
# 爷节点作为最大值
self.grandpa_l = self.get_max() + 1
# 爷节点作为最小值
self.grandpa_r = self.get_min()
def get_max(self):
max_node = self.right or self
return max_node.val
def get_min(self):
min_node = self.left or self
return min_node.val
def is_sorted(self):
if self.left and self.left.val >= self.val:
return False
if self.right and self.val > self.right.val:
return False
if self.get_max() >= self.grandpa_l:
return False
if self.get_min() < self.grandpa_r:
return False
return True
def is_search_tree(treeNode):
if not treeNode.is_sorted():
return False
left_flag = right_flag = True
if treeNode.left:
treeNode.left.grandpa_l = treeNode.val
left_flag = is_search_tree(treeNode.left)
if treeNode.right:
treeNode.right.grandpa_r = treeNode.val
right_flag = is_search_tree(treeNode.right)
return left_flag and right_flag
# 测试代码
if __name__ == '__main__':
left1 = TreeNode(1)
right1 = TreeNode(3)
tree1 = TreeNode(2, left1, right1)
left2 = TreeNode(5)
right2 = TreeNode(7)
tree2 = TreeNode(6, left2, right2)
tree = TreeNode(4, tree1, tree2)
print(is_search_tree(tree1))
print(is_search_tree(tree2))
print(is_search_tree(tree))