搜索二叉树为中序遍历升序判断
通过改变非递归版本的打印行为部分即可
import sys
class Node(object):
def __init__(self,val=None):
self.val = val
self.left = None
self.right = None
#非递归版本
#中序遍历把打印的时机换成比较
def isBST(head):
if not head:
return True
stack = []
pre = -sys.maxsize
while stack or head != None:
if head != None:
stack.append(head)
head = head.left
else:
head = stack.pop()
print(head.val, end=' ')
if head.val>pre:
pre = head.val
head = head.right
else:
return False
return True
if __name__ == '__main__':
head = Node(5)
head.left = Node(3)
head.left.left = Node(2)
head.left.right = Node(4)
head.right = Node(8)
head.right.left = Node(6)
head.right.right = Node(10)
a = isBST(head)
print(a)