Skip to content

Commit 50e7143

Browse files
ongzxChi Hi OngGouravRusiya30
authored
Add leetcode #98 solution (#65)
Co-authored-by: Chi Hi Ong <[email protected]> Co-authored-by: Gourav Rusiya <[email protected]>
1 parent 240df0e commit 50e7143

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
*
3+
* Given a binary tree, determine if it is a valid binary search tree (BST).
4+
*
5+
* Assume a BST is defined as follows:
6+
*
7+
* The left subtree of a node contains only nodes with keys less than the node's key.
8+
* The right subtree of a node contains only nodes with keys greater than the node's key.
9+
* Both the left and right subtrees must also be binary search trees.
10+
*
11+
* Example 1:
12+
13+
2
14+
/ \
15+
1 3
16+
17+
Input: [2,1,3]
18+
Output: true
19+
Example 2:
20+
21+
5
22+
/ \
23+
1 4
24+
/ \
25+
3 6
26+
27+
Input: [5,1,4,null,null,3,6]
28+
Output: false
29+
Explanation: The root node's value is 5 but its right child's value is 4.
30+
*/
31+
32+
var isValidBST = function (
33+
root,
34+
lower = Number.MIN_SAFE_INTEGER,
35+
upper = Number.MAX_SAFE_INTEGER
36+
) {
37+
if (!root) return true;
38+
39+
let value = root.val;
40+
if (value <= lower || value >= upper) {
41+
return false;
42+
}
43+
44+
if (!isValidBST(root.right, value, upper)) {
45+
return false;
46+
}
47+
48+
if (!isValidBST(root.left, lower, value)) {
49+
return false;
50+
}
51+
return true;
52+
};

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
189189
| 124 | [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) | [C++](./C++/Binary-Tree-Maximum-Path-Sum.cpp) | _O(n)_ | _O(n)_ | Hard | Tree | |
190190
| 1028 | [Recover a Tree From Preorder Traversal](https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/) | [C++](./C++/Recover-a-Tree-From-Preorder-Traversal.cpp) | _O(n)_ | _O(n)_ | Hard | Tree | |
191191
| 968 | [Binary Tree Cameras](https://leetcode.com/problems/binary-tree-cameras/) | [C++](./C++/Binary-Tree-Cameras.cpp) | _O(n)_ | _O(logn)_ | Hard | Binary Tree, Dynamic Programming
192-
192+
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) | [Javascript](./JavaScript/98.Validate-Binary-Search-Tree.js) | _O(log(n))_ | _O(log(n))_ | Medium | Binary Tree
193193

194194
<br/>
195195
<div align="right">

0 commit comments

Comments
 (0)