Validate Binary Search Tree
MediumTrees
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 values less than the node's value.
- The right subtree of a node contains only nodes with values greater than the node's value.
- Both the left and right subtrees must also be valid BSTs.
The tree is represented as a nested object: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } }
Example 1:
Input: root = [2,1,3]
2
/ \
1 3
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The root's right child is 4, which is less than 5.
Constraints:
- •
1 <= number of nodes <= 10^4 - •
-2^31 <= Node.val <= 2^31 - 1
Validate Binary Search Tree
MediumTrees
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 values less than the node's value.
- The right subtree of a node contains only nodes with values greater than the node's value.
- Both the left and right subtrees must also be valid BSTs.
The tree is represented as a nested object: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } }
Example 1:
Input: root = [2,1,3]
2
/ \
1 3
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
5
/ \
1 4
/ \
3 6
Output: false
Explanation: The root's right child is 4, which is less than 5.
Constraints:
- •
1 <= number of nodes <= 10^4 - •
-2^31 <= Node.val <= 2^31 - 1
Press Run or Ctrl+Enter to execute