2026-06-01 18:12:40 +08:00
|
|
|
#+ANKI_DECK: study_deck_02
|
2026-06-01 17:12:10 +08:00
|
|
|
* TODO 0098. Validate Binary Search Tree :medium:
|
2026-06-01 02:33:30 +08:00
|
|
|
:PROPERTIES:
|
2026-06-01 17:22:07 +08:00
|
|
|
:NEETCODE: [[file:../../roadmap.org::*0098. Validate Binary Search Tree][0098. Validate Binary Search Tree]]
|
2026-06-01 02:33:30 +08:00
|
|
|
:END:
|
|
|
|
|
|
2026-06-01 17:22:07 +08:00
|
|
|
Given the ~root~ of a binary tree, /determine if it is a valid binary search tree (BST)/.
|
|
|
|
|
|
|
|
|
|
A *valid BST* is defined as follows:
|
|
|
|
|
|
|
|
|
|
- The left subtree of a node contains only nodes with keys *strictly less than* the node's key.
|
|
|
|
|
|
|
|
|
|
- The right subtree of a node contains only nodes with keys *strictly greater than* the node's key.
|
|
|
|
|
|
|
|
|
|
- Both the left and right subtrees must also be binary search trees.
|
|
|
|
|
|
|
|
|
|
*Example 1:*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#+begin_src
|
|
|
|
|
Input: root = [2,1,3]
|
|
|
|
|
Output: true
|
|
|
|
|
#+end_src
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
*Example 2:*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#+begin_src
|
|
|
|
|
Input: root = [5,1,4,null,null,3,6]
|
|
|
|
|
Output: false
|
|
|
|
|
Explanation: The root node's value is 5 but its right child's value is 4.
|
|
|
|
|
#+end_src
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
*Constraints:*
|
|
|
|
|
|
|
|
|
|
- The number of nodes in the tree is in the range ~[1, 10^{4}]~.
|
|
|
|
|
|
|
|
|
|
- ~-2^{31} <= Node.val <= 2^{31} - 1~
|
|
|
|
|
|
2026-06-01 02:39:53 +08:00
|
|
|
** TODO Approach
|
|
|
|
|
Write your approach here.
|
|
|
|
|
|
|
|
|
|
** TODO Python
|
2026-06-05 22:32:49 +08:00
|
|
|
#+begin_src python :lc-problem 98 :lc-lang python3
|
2026-06-01 17:22:07 +08:00
|
|
|
# Definition for a binary tree node.
|
|
|
|
|
# class TreeNode:
|
|
|
|
|
# def __init__(self, val=0, left=None, right=None):
|
|
|
|
|
# self.val = val
|
|
|
|
|
# self.left = left
|
|
|
|
|
# self.right = right
|
|
|
|
|
class Solution:
|
|
|
|
|
def isValidBST(self, root: Optional[TreeNode]) -> bool:
|
2026-06-01 02:39:53 +08:00
|
|
|
#+end_src
|
|
|
|
|
|
|
|
|
|
** TODO C++
|
2026-06-05 22:32:49 +08:00
|
|
|
#+begin_src cpp :lc-problem 98
|
2026-06-01 17:22:07 +08:00
|
|
|
/**
|
|
|
|
|
* Definition for a binary tree node.
|
|
|
|
|
* struct TreeNode {
|
|
|
|
|
* int val;
|
|
|
|
|
* TreeNode *left;
|
|
|
|
|
* TreeNode *right;
|
|
|
|
|
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
|
|
|
|
|
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
|
|
|
|
|
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
|
|
|
|
|
* };
|
|
|
|
|
*/
|
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
bool isValidBST(TreeNode* root) {
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-06-01 02:33:30 +08:00
|
|
|
#+end_src
|