-
Notifications
You must be signed in to change notification settings - Fork 891
/
problem_093.py
100 lines (84 loc) · 2.14 KB
/
problem_093.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import sys
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __repr__(self):
string = "val={}:(left={}, right={})".format(
self.val, self.left, self.right)
return string
def get_largest_bst_helper(node):
if not node:
return (True, node, 0, sys.maxsize, -sys.maxsize)
if not node.left and not node.right:
return (True, node, 1, node.val, node.val)
left_is_bst, left_bst, left_nodes, left_minval, left_maxval = \
get_largest_bst_helper(node.left)
right_is_bst, right_bst, right_nodes, right_minval, right_maxval = \
get_largest_bst_helper(node.right)
if left_is_bst and right_is_bst:
if node.left and node.right:
if node.val >= left_maxval and node.val <= right_minval:
return (True, node, left_nodes + right_nodes + 1,
left_minval, right_maxval)
elif node.left and node.val >= left_maxval:
return (True, node, left_nodes + 1, left_minval, node.val)
elif node.right and node.val >= right_minval:
return (True, node, left_nodes + 1, node.val, right_maxval)
if left_nodes > right_nodes:
return (False, left_bst, left_nodes, left_minval, node.val)
else:
return (False, right_bst, right_nodes, node.val, right_maxval)
def get_largest_bst(root):
_, largest_bst, nodes, _, _ = get_largest_bst_helper(root)
return (largest_bst, nodes)
# tests
a = Node(3)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(3)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert get_largest_bst(a) == (a, 6)
a = Node(1)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(3)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert get_largest_bst(a) == (b, 3)
a = Node(3)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(4)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert get_largest_bst(a) == (b, 3)
a = Node(3)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(1)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert get_largest_bst(a) == (c, 2)