题目:实现一个函数,检查一棵二叉树是否为二叉搜索树。
解题思路:中序遍历后检查是否是递增序列,是因为用python的人少吗?内存和时间还能击败好大百分比用户呢?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def helper(root,ll):
if root:
if root.left:
helper(root.left,ll)
ll.append(root.val)
if root.right:
helper(root.right,ll)
lla=[]
helper(root,lla)
for i in range(len(lla)-1):
if lla[i]>=lla[i+1]:
return False
return True