Skip to content

Commit 5161060

Browse files
committed
Add solution for 19. Remove Nth Node From End of List
1 parent 4560634 commit 5161060

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
98. Validate Binary Search Tree
3+
https://leetcode.com/problems/validate-binary-search-tree/
4+
5+
6+
"""
7+
from typing import Optional
8+
9+
class TreeNode:
10+
def __init__(self, val=0, left=None, right=None):
11+
self.val = val
12+
self.left = left
13+
self.right = right
14+
15+
16+
"""
17+
Solution1:
18+
Recursion
19+
In the given problem, the subtree of a node has a range of values according to the previous nodes.
20+
Thus, we can define a function that checks the validity of the subtree of a node with the range of values.
21+
22+
- Define a function that checks the validity of the subtree of a node with the range of values
23+
- Check the validity of the left subtree and the right subtree
24+
- with the range of values that the left subtree and the right subtree should have
25+
- If left < root < right, the subtree is valid
26+
- If the left subtree and the right subtree are valid, call the function recursively for the left and right subtrees.
27+
- before calling the function, update the range of values for the left and right subtrees
28+
- If the left subtree and the right subtree are valid, return True
29+
30+
Time complexity: O(N)
31+
- The function is called recursively for each node
32+
33+
Space complexity: O(N)
34+
- The function stores the range of values for each node
35+
"""
36+
37+
class Solution1:
38+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
39+
maximum = float('inf')
40+
minimum = float('-inf')
41+
return self.isValidSubTree(
42+
root, maximum, minimum
43+
)
44+
45+
def isValidSubTree(self, root, maximum, minimum):
46+
if root.left is not None:
47+
if root.val <= root.left.val:
48+
return False
49+
if not minimum < root.left.val < maximum:
50+
return False
51+
52+
if root.right is not None :
53+
if root.val >= root.right.val:
54+
return False
55+
if not minimum < root.right.val < maximum:
56+
return False
57+
58+
if root.left is not None:
59+
l_max = min(maximum, root.val)
60+
is_left_valid = self.isValidSubTree(
61+
root.left, l_max, minimum
62+
)
63+
else:
64+
is_left_valid = True
65+
66+
if root.right is not None:
67+
r_min = max(minimum, root.val)
68+
is_right_valid = self.isValidSubTree(
69+
root.right, maximum, r_min
70+
)
71+
else:
72+
is_right_valid = True
73+
74+
if is_left_valid and is_right_valid:
75+
return True
76+
else:
77+
return False

0 commit comments

Comments
 (0)