{"id":10237,"date":"2025-10-13T10:50:55","date_gmt":"2025-10-13T05:20:55","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10237"},"modified":"2025-10-13T10:50:55","modified_gmt":"2025-10-13T05:20:55","slug":"validate-binary-search-tree","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/validate-binary-search-tree\/","title":{"rendered":"Validate Binary Search Tree"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n  }\n\n  .wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n  }\n\n  .wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n  }\n\n  .wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-content > pre {\n    background: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-content.active {\n    display: block !important;\n  }\n\n  .wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n  }\n\n  .wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n  }\n\n  .wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n  }\n\n  .wp_blog_explanation h1,\n  .wp_blog_explanation h2,\n  .wp_blog_explanation h3,\n  .wp_blog_explanation h4,\n  .wp_blog_explanation h5,\n  .wp_blog_explanation h6,\n  .wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n  }\n<\/style>\n<div class=\"wp_blog_explanation\">\n    <p>Given the root of a binary tree, determine if it is a valid binary search tree (BST).<\/p>\n    \n    <h2>Definition of BST<\/h2>\n    <ul>\n      <li>The left subtree of a node contains only nodes with keys <strong>strictly less<\/strong> than the node&#8217;s key.<\/li>\n      <li>The right subtree of a node contains only nodes with keys <strong>strictly greater<\/strong> than the node&#8217;s key.<\/li>\n      <li>Both left and right subtrees must also be binary search trees.<\/li>\n    <\/ul>\n  \n    <h2>Input \/ Output<\/h2>\n    <p><strong>Input:<\/strong> <code>root = [2,1,3]<\/code><\/p>\n    <p><strong>Output:<\/strong> <code>true<\/code><\/p>\n  \n    <p><strong>Input:<\/strong> <code>root = [5,1,4,null,null,3,6]<\/code><\/p>\n    <p><strong>Output:<\/strong> <code>false<\/code><\/p>\n    <p><strong>Explanation:<\/strong> The root node&#8217;s value is 5 but its right child&#8217;s value is 4, which violates BST property.<\/p>\n  \n    <h2>Approach<\/h2>\n    <ul>\n      <li>Use recursion with range limits.<\/li>\n      <li>At each node, ensure its value is within valid range: <code>(lo &lt; node.val &lt; hi)<\/code>.<\/li>\n      <li>Update the range for the left and right child accordingly.<\/li>\n      <li>Base case: null nodes are valid BSTs.<\/li>\n    <\/ul>\n  \n    <h2>Time &#038; Space Complexity<\/h2>\n    <ul>\n      <li><strong>Time Complexity:<\/strong> O(n) \u2014 visit each node once.<\/li>\n      <li><strong>Space Complexity:<\/strong> O(h) \u2014 where h is the height of the tree due to recursion stack.<\/li>\n    <\/ul>\n  <\/div>\n  \n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c#\">C#<\/button>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n  var isValidBST = function (curr, lo = null, hi = null) {\n      if (!curr) return true;\n  \n      if ((lo !== null && curr.val <= lo) ||\n          (hi !== null &#038;&#038; curr.val >= hi)) {\n          return false;\n      }\n  \n      let isLeftBST = isValidBST(curr.left, lo, curr.val);\n      let isRightBST = isValidBST(curr.right, curr.val, hi);\n  \n      return isLeftBST && isRightBST;\n  };\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n  struct TreeNode {\n      int val;\n      TreeNode *left;\n      TreeNode *right;\n      TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n  };\n  \n  bool isValidBST(TreeNode* root, TreeNode* lo = nullptr, TreeNode* hi = nullptr) {\n      if (!root) return true;\n      if ((lo && root->val <= lo->val) || (hi && root->val >= hi->val)) return false;\n      return isValidBST(root->left, lo, root) && isValidBST(root->right, root, hi);\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n  \/\/ Definition for a binary tree node\n  struct TreeNode {\n      int val;\n      struct TreeNode *left;\n      struct TreeNode *right;\n  };\n  \n  bool isValidBSTHelper(struct TreeNode* root, long long lo, long long hi) {\n      if (!root) return true;\n      if (root->val <= lo || root->val >= hi) return false;\n      return isValidBSTHelper(root->left, lo, root->val) &&\n             isValidBSTHelper(root->right, root->val, hi);\n  }\n  \n  bool isValidBST(struct TreeNode* root) {\n      return isValidBSTHelper(root, LONG_MIN, LONG_MAX);\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\n  class TreeNode {\n      int val;\n      TreeNode left, right;\n      TreeNode(int x) { val = x; }\n  }\n  \n  public class Solution {\n      public boolean isValidBST(TreeNode root) {\n          return validate(root, null, null);\n      }\n  \n      private boolean validate(TreeNode node, Integer lo, Integer hi) {\n          if (node == null) return true;\n          if ((lo != null && node.val <= lo) || (hi != null &#038;&#038; node.val >= hi)) return false;\n          return validate(node.left, lo, node.val) &&\n                 validate(node.right, node.val, hi);\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\n  class TreeNode:\n      def __init__(self, val=0, left=None, right=None):\n          self.val = val\n          self.left = left\n          self.right = right\n  \n  def isValidBST(root, lo=None, hi=None):\n      if not root:\n          return True\n      if (lo is not None and root.val <= lo) or (hi is not None and root.val >= hi):\n          return False\n      return isValidBST(root.left, lo, root.val) and isValidBST(root.right, root.val, hi)\n      <\/code><\/pre>\n    <\/div>\n  \n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c#\">\n      <pre><code class=\"language-csharp\">\n  public class TreeNode {\n      public int val;\n      public TreeNode left;\n      public TreeNode right;\n      public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {\n          this.val = val;\n          this.left = left;\n          this.right = right;\n      }\n  }\n  \n  public class Solution {\n      public bool IsValidBST(TreeNode root) {\n          return Validate(root, null, null);\n      }\n  \n      private bool Validate(TreeNode node, int? lo, int? hi) {\n          if (node == null) return true;\n          if ((lo != null && node.val <= lo) || (hi != null &#038;&#038; node.val >= hi)) return false;\n          return Validate(node.left, lo, node.val) && Validate(node.right, node.val, hi);\n      }\n  }\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n  \n\n\n  <a href=\"https:\/\/leetcode.com\/problems\/validate-binary-search-tree\/description\/\" target=\"blank\">Solve this problem.<\/a>\n  <script>\n  document.addEventListener(\"DOMContentLoaded\", function () {\n    const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n    const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n    buttons.forEach((button) => {\n      button.addEventListener(\"click\", () => {\n        const lang = button.getAttribute(\"data-lang\");\n\n        buttons.forEach((btn) => btn.classList.remove(\"active\"));\n        button.classList.add(\"active\");\n\n        contents.forEach((content) => {\n          content.classList.toggle(\"active\", content.getAttribute(\"data-lang\") === lang);\n        });\n      });\n    });\n  });\n<\/script>\n\n\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given the root of a binary tree, determine if it is a valid binary search tree (BST). Definition of BST The left subtree of a node contains only nodes with keys strictly less than the node&#8217;s key. The right subtree of a node contains only nodes with keys strictly greater than the node&#8217;s key. Both<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[811],"tags":[],"class_list":{"0":"post-10237","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-data-structures-and-algorithms"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10237","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10237"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10237\/revisions"}],"predecessor-version":[{"id":10238,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10237\/revisions\/10238"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10237"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10237"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10237"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}