{"id":770,"date":"2017-11-11T20:03:21","date_gmt":"2017-11-12T04:03:21","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=770"},"modified":"2018-11-16T12:45:20","modified_gmt":"2018-11-16T20:45:20","slug":"leetcode-98-validate-binary-search-tree","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-98-validate-binary-search-tree\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 98. Validate Binary Search Tree"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 98. Validate Binary Search Tree - \u5237\u9898\u627e\u5de5\u4f5c EP104\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/Jq0Wk9xeQ0U?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Given a binary tree, determine if it is a valid binary search tree (BST).<\/p>\n<p>Assume a BST is defined as follows:<\/p>\n<ul>\n<li>The left subtree of a node contains only nodes with keys\u00a0<b>less than<\/b>\u00a0the node&#8217;s key.<\/li>\n<li>The right subtree of a node contains only nodes with keys\u00a0<b>greater than<\/b>\u00a0the node&#8217;s key.<\/li>\n<li>Both the left and right subtrees must also be binary search trees.<\/li>\n<\/ul>\n<p><b>Example 1:<\/b><\/p>\n<pre>    2\r\n   \/ \\\r\n  1   3\r\n<\/pre>\n<p>Binary tree\u00a0<code>[2,1,3]<\/code>, return true.<\/p>\n<p><b>Example 2:<\/b><\/p>\n<pre>    1\r\n   \/ \\\r\n  2   3\r\n<\/pre>\n<p>Binary tree\u00a0<code>[1,2,3]<\/code>, return false.<\/p>\n<h1><strong>Solution 1<\/strong><\/h1>\n<p>Traverse the tree and limit the range of each subtree and check whether root&#8217;s value is in the range.<\/p>\n<p>Time complexity: O(n)<\/p>\n<p>Space complexity: O(n)<\/p>\n<p>Note: in order to cover the range of -2^31 ~ 2^31-1, we need to use long or nullable integer.<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++\/long<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">class Solution {\r\npublic:\r\n    bool isValidBST(TreeNode* root) {\r\n        return isValidBST(root, LLONG_MIN, LLONG_MAX);\r\n    }\r\nprivate:\r\n    bool isValidBST(TreeNode* root, long min_val, long max_val) {\r\n        if (!root) return true;\r\n        if (root-&gt;val &lt;= min_val || root-&gt;val &gt;= max_val)\r\n            return false; \r\n        return isValidBST(root-&gt;left, min_val, root-&gt;val)\r\n            &amp;&amp; isValidBST(root-&gt;right, root-&gt;val, max_val);\r\n    }\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">C++\/nullable<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true \">class Solution {\r\npublic:\r\n    bool isValidBST(TreeNode* root) {\r\n        return isValidBST(root, nullptr, nullptr);\r\n    }\r\nprivate:\r\n    bool isValidBST(TreeNode* root, int* min_val, int* max_val) {\r\n        if (!root) return true;\r\n        if ((min_val &amp;&amp; root-&gt;val &lt;= *min_val) \r\n          ||(max_val &amp;&amp; root-&gt;val &gt;= *max_val))\r\n            return false;\r\n        \r\n        return isValidBST(root-&gt;left, min_val, &amp;root-&gt;val)\r\n            &amp;&amp; isValidBST(root-&gt;right, &amp;root-&gt;val, max_val);\r\n    }\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java\/nullable<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 1 ms\r\nclass Solution {\r\n  public boolean isValidBST(TreeNode root) {\r\n    return isValidBST(root, null, null);\r\n  }\r\n  \r\n  private boolean isValidBST(TreeNode root, Integer min, Integer max) {\r\n    if (root == null) return true;\r\n    if ((min != null &amp;&amp; root.val &lt;= min) \r\n      ||(max != null &amp;&amp; root.val &gt;= max))\r\n        return false;\r\n\r\n    return isValidBST(root.left, min, root.val)\r\n        &amp;&amp; isValidBST(root.right, root.val, max);\r\n  }\r\n}<\/pre>\n<\/div><\/div>\n<h1><strong>Solution 2<\/strong><\/h1>\n<p>Do an in-order traversal, the numbers should be sorted, thus we only need to compare with the previous number.<\/p>\n<p>Time complexity: O(n)<\/p>\n<p>Space complexity: O(n)<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">class Solution {\r\npublic:\r\n    bool isValidBST(TreeNode* root) {\r\n        prev_ = nullptr;\r\n        return inOrder(root);\r\n    }\r\nprivate:\r\n    TreeNode* prev_;\r\n    bool inOrder(TreeNode* root) {\r\n        if (!root) return true;\r\n        if (!inOrder(root-&gt;left)) return false;\r\n        if (prev_ &amp;&amp; root-&gt;val &lt;= prev_-&gt;val) return false;    \r\n        prev_ = root;\r\n        return inOrder(root-&gt;right);\r\n    }\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Java<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:java decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 1 ms\r\nclass Solution {\r\n  private TreeNode prev;\r\n  public boolean isValidBST(TreeNode root) {\r\n    prev = null;\r\n    return inOrder(root);\r\n  }\r\n  \r\n  private boolean inOrder(TreeNode root) {\r\n    if (root == null) return true;\r\n    if (!inOrder(root.left)) return false;\r\n    if (prev != null &amp;&amp; root.val &lt;= prev.val) return false;\r\n    prev = root;\r\n    return inOrder(root.right);\r\n  }\r\n}<\/pre>\n<\/div><\/div>\n<h1><strong>Related Problem<\/strong><\/h1>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-530-minimum-absolute-difference-in-bst\/\">\u82b1\u82b1\u9171 LeetCode 530. Minimum Absolute Difference in BST<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[164,45],"tags":[74,177,28],"class_list":["post-770","post","type-post","status-publish","format-standard","hentry","category-medium","category-tree","tag-bst","tag-medium","tag-tree","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/770","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=770"}],"version-history":[{"count":12,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/770\/revisions"}],"predecessor-version":[{"id":4326,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/770\/revisions\/4326"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=770"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=770"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=770"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}