Leetcode 98.验证二叉搜索树

方法

方法1:递归(中序遍历)

中序遍历二叉搜索树,一般可以得到递增的中序序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class 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:非递归中序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class 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