{"id":27225,"date":"2018-01-05T21:42:55","date_gmt":"2018-01-05T16:12:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27225"},"modified":"2018-10-31T10:05:00","modified_gmt":"2018-10-31T04:35:00","slug":"python-program-check-binary-tree-bst-not","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-program-check-binary-tree-bst-not\/","title":{"rendered":"Check if a binary tree is BST or not"},"content":{"rendered":"<p><span style=\"color: #008080;\"><strong>Python program to check if a binary tree is BST:<\/strong><\/span><\/p>\n<p>A <a href=\"https:\/\/www.wikitechy.com\/technology\/python-program-inorder-successor-binary-search-tree\/\" target=\"_blank\" rel=\"noopener\">binary search tree<\/a> (<strong>BST<\/strong>) is a node based binary tree <a href=\"https:\/\/www.wikitechy.com\/interview-questions\/data-structure\/what-is-data-structure\" target=\"_blank\" rel=\"noopener\">data structure<\/a> which has the following properties.<span id=\"more-3042\"><\/span><br \/>\n\u2022 The<strong> left subtree<\/strong> of a node contains only nodes with <strong>keys less than<\/strong> the node\u2019s key.<br \/>\n\u2022 The <strong>right subtree<\/strong> of a node contains only nodes with <strong>keys greater than<\/strong> the node\u2019s key.<br \/>\n\u2022 Both the left and right subtrees must also be binary search trees.<\/p>\n<p><strong>From the above properties it naturally follows that:<\/strong><br \/>\nEach node (item in the <a href=\"https:\/\/www.wikitechy.com\/technology\/python-program-lowest-common-ancestor-binary-search-tree\/\" target=\"_blank\" rel=\"noopener\">tree<\/a>) has a <strong>distinct key.<\/strong><\/p>\n<div id=\"practice\">\n<h4 id=\"ad-typebanner\">[ad type=&#8221;banner&#8221;]<\/h4>\n<\/div>\n<h3 id=\"method-1-correct-and-efficient\"><span style=\"color: #0000ff;\"><strong>METHOD 1 (Correct and Efficient)<\/strong><\/span><\/h3>\n<p>A better solution looks at each node only once. The trick is to write a utility helper function <strong>isBSTUtil(struct node* node, int min, int max)<\/strong> that <a href=\"https:\/\/www.wikitechy.com\/technology\/python-programming-tree-traversals-inorder-preorder-postorder\/\" target=\"_blank\" rel=\"noopener\">traverses<\/a> down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be<strong> INT_MIN and INT_MAX<\/strong> \u2014 they narrow from there.<\/p>\n<pre>\/* Returns true if the given tree is a binary search tree \r\n (efficient version). *\/ \r\nint isBST(struct node* node) \r\n{ \r\n  return(isBSTUtil(node, INT_MIN, INT_MAX)); \r\n} \r\n\r\n\/* Returns true if the given tree is a BST and its \r\n values are &gt;= min and &lt;= max. *\/ \r\nint is BST Util(struct node* node, int min, int max)<\/pre>\n<h3 id=\"implementation-of-python-program\"><span style=\"color: #333300;\"><strong>Implementation of Python Program:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python Programming<\/span> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to check if a binary tree is bst or not<br\/> <br\/>INT_MAX = 4294967296<br\/>INT_MIN = -4294967296<br\/> <br\/># A binary tree node<br\/>class Node:<br\/> <br\/>    # Constructor to create a new node<br\/>    def __init__(self, data):<br\/>        self.data = data <br\/>        self.left = None<br\/>        self.right = None<br\/> <br\/> <br\/># Returns true if the given tree is a binary search tree<br\/># (efficient version)<br\/>def isBST(node):<br\/>    return (isBSTUtil(node, INT_MIN, INT_MAX))<br\/> <br\/># Retusn true if the given tree is a BST and its values<br\/># &gt;= min and &lt;= max<br\/>def isBSTUtil(node, mini, maxi):<br\/>     <br\/>    # An empty tree is BST<br\/>    if node is None:<br\/>        return True<br\/> <br\/>    # False if this node violates min\/max constraint<br\/>    if node.data &lt; mini or node.data &gt; maxi:<br\/>        return False<br\/> <br\/>    # Otherwise check the subtrees recursively<br\/>    # tightening the min or max constraint<br\/>    return (isBSTUtil(node.left, mini, node.data -1) and<br\/>          isBSTUtil(node.right, node.data+1, maxi))<br\/> <br\/># Driver program to test above function<br\/>root = Node(4)<br\/>root.left = Node(2)<br\/>root.right = Node(5)<br\/>root.left.left = Node(1)<br\/>root.left.right = Node(3)<br\/> <br\/>if (isBST(root)):<br\/>    print &quot;Is BST&quot;<br\/>else:<br\/>    print &quot;Not a BST&quot;<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Is BST<\/pre>\n<p><span style=\"color: #333300;\"><strong>Time Complexity:<\/strong> <\/span><strong>O(n)\u00a0<\/strong><br \/>\n<span style=\"color: #333300;\"><strong>Auxiliary Space :<\/strong><\/span> <strong>O(1)<\/strong> if Function Call Stack size is not considered, otherwise O(n)<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Python program to check if a binary tree is BST or not &#8211; Data Structure &#8211; A binary search tree is a node based binary tree data structure.<\/p>\n","protected":false},"author":1,"featured_media":28088,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80126,1,4148],"tags":[81149,81152,81143,81142,81145,81146,81148,81147,81150,81141,81144,81151],"class_list":["post-27225","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-binary-search-tree","category-coding","category-python","tag-check-if-binary-tree-is-balanced","tag-check-if-binary-tree-is-balanced-python","tag-check-if-binary-tree-is-bst-c","tag-check-if-binary-tree-is-bst-java","tag-check-if-binary-tree-is-bst-python","tag-check-whether-the-linked-list-is-palindrome","tag-geeksforgeeks-binary-search-tree","tag-how-to-check-if-a-tree-is-balanced-or-not-in-java","tag-python-check-if-tree-is-balanced","tag-searches-related-to-python-program-to-check-if-a-binary-tree-is-bst-or-not","tag-valid-binary-search-tree","tag-what-is-balanced-binary-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27225","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27225"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27225\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/28088"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27225"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27225"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27225"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}