-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path098. Validate Binary Search Tree.py
70 lines (60 loc) · 1.89 KB
/
098. Validate Binary Search Tree.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Given a binary tree, determine if it is a valid binary search tree (BST).
# Assume a BST is defined as follows:
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
# Example 1:
# 2
# / \
# 1 3
# Binary tree [2,1,3], return true.
# Example 2:
# 1
# / \
# 2 3
# Binary tree [1,2,3], return false.
# 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
"""
return self.isValidBSThelper(root, float("-inf"), float("inf"))
def isValidBSThelper(self,root,left,right):
if not root:
return True
if left >= root.val or right <= root.val:
return False
return self.isValidBSThelper(root.left, left, root.val) and self.isValidBSThelper(root.right, root.val, right)
# 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
"""
res = []
flag = [True]
self.check(root, res,flag)
# print res
return True if flag[0] else False
def check(self,root,res,flag):
if not root:
return
self.check(root.left, res,flag)
if res and root.val <= res[-1]:
flag[0] = False
return
res.append(root.val)
self.check(root.right, res, flag)