Leetcode 98.验证二叉搜索树 Posted on 2019-02-18 | 方法方法1:递归(中序遍历)中序遍历二叉搜索树,一般可以得到递增的中序序列 123456789101112131415161718192021222324252627282930# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True output=[] self.inorder(root,output) for i in range(1,len(output)): if output[i]<=output[i-1]: return False return True def inorder(self,root,output): if not root: return self.inorder(root.left,output) output.append(root.val) self.inorder(root.right,output) 方法2:非递归中序遍历12345678910111213141516171819202122232425# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack=[] ans=[] while root or stack: while root: stack.append(root) root=root.left root=stack.pop() ans.append(root.val) if len(ans)>=2 and ans[-1]<=ans[-2]: return False root=root.right return True Leetcode Discussion:Python version based on inorder traversal