1.二叉排序树定义
二叉排序树(BinarySortTree)定义如下:
二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
2.判断方法
已知二叉排序树的中序遍历后的顺序是递增的,所以解决方法是以非递归的中序遍历遍历二叉树,判断如果有任何一个值大于它的后继结点的值,那么它就不是二叉排序树,直接返回false。
1.定义一个栈:
#定义一个栈
class Stack:
__index=-1
__stack=[]
def push(self,value):
if value:
self.__stack.append(value)
self.__index+=1
def pop(self):
value=None
if self.__index>-1:
value=self.__stack.pop(self.__index)
self.__index-=1
return value
def isEmpty(self):
if self.__index>-1:
return False
return True
2.判断方法
def IsBainarySortTree(head):
#定义一个栈
stack=Stack()
judge=[True]#判断是否为是二叉排序树
maxValue=-2147483647
current=head
#print(type(current),'current')
while current !=None or not stack.isEmpty():
if judge[0]==False:
break
while current!=None:
stack.push(current)
current=current.get_lChild()
t1=stack.pop()
if maxValue<=t1.get_value():
maxValue=t1.get_value()
else:
judge[0]=False
if current!=None and current.get_rChild()!=None:
current=current.get_rChild()
else:
current=None
return judge[0]
3.测试
定义一颗BST
bst=bst.BinarySortTree(7)
num=[8,4,5,6,11]
for i in num:
bst.insert(i,bst)
print(IsBainarySortTree(bst))
输出结果:
True
进程已结束,退出代码0
定义一棵非BST
t1=tree.Tree(5)
t2=tree.Tree(4)
t3=tree.Tree(6)
t1.set_lChiled(t3)
t2.set_rChild(t2)
print(IsBainarySortTree(t1))
输出结果:
False
进程已结束,退出代码0
完整版代码:
def IsBainarySortTree(head):
#定义一个栈
stack=Stack()
judge=[True]#判断是否为是二叉排序树
maxValue=-2147483647
current=head
#print(type(current),'current')
while current !=None or not stack.isEmpty():
if judge[0]==False:
break
while current!=None:
stack.push(current)
#print(current,'current=')
current=current.get_lChild()
t1=stack.pop()
if maxValue<=t1.get_value():
maxValue=t1.get_value()
else:
judge[0]=False
if current!=None and current.get_rChild()!=None:
current=current.get_rChild()
else:
current=None
return judge[0]
#定义一个栈
class Stack:
__index=-1
__stack=[]
def push(self,value):
if value:
self.__stack.append(value)
self.__index+=1
def pop(self):
value=None
if self.__index>-1:
value=self.__stack.pop(self.__index)
self.__index-=1
return value
def isEmpty(self):
if self.__index>-1:
return False
return True