Validate Binary Search Tree🚂

Photo by Shane Hauser on Unsplash

Question

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 less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [2,1,3]
Output: true

Example 2:

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.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1

Java Solution

Time complexity of below solution
O(n) since we are visiting each node only once.

Code

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DockerCon 2022: Containerizing The World

What does it mean to be a “Full-Stack” Developer in 2022?

Leetcode #994 Rotting Oranges

Integration with Git, GitHub.

Creating Modular Powerup Systems

Server-Side : Flask + MongoDB + Project Structure

Quickly changing directories in your terminal

Android and Dagger: AndroidInjection

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tehleel Mir 🐢

Tehleel Mir 🐢

More from Medium

Minimum Depth of Binary Tree🛩

Understanding Recursion | Binary Tree

Merge Sort for Linked Lists