{"id":27224,"date":"2018-01-05T21:45:21","date_gmt":"2018-01-05T16:15:21","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27224"},"modified":"2018-10-29T11:16:17","modified_gmt":"2018-10-29T05:46:17","slug":"java-program-check-binary-tree-bst-not","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-program-check-binary-tree-bst-not\/","title":{"rendered":"Java program to check if a binary tree is BST or not"},"content":{"rendered":"<h2 id=\"binary-search-tree-bst\">Binary Search Tree (BST):<\/h2>\n<p>A <a href=\"https:\/\/www.wikitechy.com\/technology\/java-program-print-bst-keys-given-range\/\" target=\"_blank\" rel=\"noopener\">binary search tree<\/a> (<strong>BST<\/strong>) is a node based <strong>binary tree data structure<\/strong> 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 keys less than the node\u2019s key.<br \/>\n\u2022 The <strong>right subtree<\/strong> of a node contains only nodes with keys greater than the node\u2019s key.<br \/>\n\u2022 Both the left and right subtrees must also be <strong>binary search trees.<\/strong><\/p>\n<p><strong>From the above properties it naturally follows that:<\/strong><br \/>\n\u2022 Each node (item in the tree) has a <strong>distinct key<\/strong>.<\/p>\n<div id=\"practice\">\n<h3 id=\"java-program-to-check-if-a-binary-tree-is-bst\"><span style=\"color: #993300;\">Java program to check if a binary tree is BST:<\/span><\/h3>\n<h3 id=\"method-1-correct-and-efficient\"><span style=\"color: #333300;\"><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 is <strong>BST Util(struct node* node, int min, int max)<\/strong> that traverses 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 isBSTUtil(struct node* node, int min, int max)<\/pre>\n<\/div>\n<h3 id=\"implementation\"><span style=\"color: #ff6600;\"><strong>Implementation:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Programming<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/Java implementation to check if given Binary tree<br\/>\/\/is a BST or not<br\/> <br\/>class Node<br\/>{<br\/>    int data;<br\/>    Node left, right;<br\/> <br\/>    public Node(int item)<br\/>    {<br\/>        data = item;<br\/>        left = right = null;<br\/>    }<br\/>}<br\/> <br\/>public class BinaryTree<br\/>{<br\/>    <br\/>    Node root;<br\/> <br\/>    <br\/>    boolean isBST()  {<br\/>        return isBSTUtil(root, Integer.MIN_VALUE,<br\/>                               Integer.MAX_VALUE);<br\/>    }<br\/> <br\/>   <br\/>    boolean isBSTUtil(Node node, int min, int max)<br\/>    {<br\/>        <br\/>        if (node == null)<br\/>            return true;<br\/> <br\/>        <br\/>        if (node.data &lt; min || node.data &gt; max)<br\/>            return false;<br\/> <br\/>       <br\/>        return (isBSTUtil(node.left, min, node.data-1) &amp;&amp;<br\/>                isBSTUtil(node.right, node.data+1, max));<br\/>    }<br\/> <br\/>    <br\/>    public static void main(String args[])<br\/>    {<br\/>        BinaryTree tree = new BinaryTree();<br\/>        tree.root = new Node(4);<br\/>        tree.root.left = new Node(2);<br\/>        tree.root.right = new Node(5);<br\/>        tree.root.left.left = new Node(1);<br\/>        tree.root.left.right = new Node(3);<br\/> <br\/>        if (tree.isBST())<br\/>            System.out.println(&quot;IS BST&quot;);<br\/>        else<br\/>            System.out.println(&quot;Not a BST&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #008000;\">Output:\u00a0<\/span><\/h3>\n<pre>IS BST<\/pre>\n<p><span style=\"color: #008080;\"><strong>Time Complexity:<\/strong> <\/span><strong>O(n)<\/strong><br \/>\n<span style=\"color: #008080;\"><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<h3 id=\"java-program-to-check-if-a-binary-tree-is-bst-2\"><span style=\"color: #003366;\">Java program to check if a binary tree is BST:<\/span><\/h3>\n<h3 id=\"method-2using-in-order-traversal\"><span style=\"color: #333300;\"><strong>METHOD 2(Using In-Order Traversal):<\/strong><\/span><\/h3>\n<p>1) Do <a href=\"https:\/\/www.wikitechy.com\/technology\/java-programming-tree-traversals-inorder-preorder-postorder\/\" target=\"_blank\" rel=\"noopener\">In-Order Traversal<\/a> of the given tree and store the result in a temp array.<br \/>\n2) Check if the temp array is sorted in ascending order, if it is, then the tree is BST.<\/p>\n<p><span style=\"color: #008080;\"><strong>Time Complexity:<\/strong><\/span> <strong>O(n)<\/strong><\/p>\n<p>We can avoid the use of Auxiliary <a href=\"https:\/\/www.wikitechy.com\/tutorials\/java\/java-arrays\" target=\"_blank\" rel=\"noopener\">Array<\/a>. While doing In-Order traversal, we can keep track of previously visited node. If the value of the currently visited node is less than the previous value, then tree is not BST.<\/p>\n<h3 id=\"implementation-2\"><span style=\"color: #ff6600;\"><strong>Implementation:<\/strong><\/span><\/h3>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Programming<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\"><br\/>class Node<br\/>{<br\/>    int data;<br\/>    Node left, right;<br\/> <br\/>    public Node(int item)<br\/>    {<br\/>        data = item;<br\/>        left = right = null;<br\/>    }<br\/>}<br\/> <br\/>public class BinaryTree<br\/>{<br\/>   <br\/>    Node root;<br\/> <br\/>  <br\/>    Node prev;<br\/> <br\/>    boolean isBST()  {<br\/>        prev = null;<br\/>        return isBST(root);<br\/>    }<br\/> <br\/>  <br\/>    boolean isBST(Node node)<br\/>    {<br\/>    <br\/>        if (node != null)<br\/>        {<br\/>            if (!isBST(node.left))<br\/>                return false;<br\/> <br\/>    <br\/>            if (prev != null &amp;&amp; node.data &lt;= prev.data )<br\/>                return false;<br\/>            prev = node;<br\/>            return isBST(node.right);<br\/>        }<br\/>        return true;<br\/>    }<br\/> <br\/><br\/>    public static void main(String args[])<br\/>    {<br\/>        BinaryTree tree = new BinaryTree();<br\/>        tree.root = new Node(4);<br\/>        tree.root.left = new Node(2);<br\/>        tree.root.right = new Node(5);<br\/>        tree.root.left.left = new Node(1);<br\/>        tree.root.left.right = new Node(3);<br\/> <br\/>        if (tree.isBST())<br\/>            System.out.println(&quot;IS BST&quot;);<br\/>        else<br\/>            System.out.println(&quot;Not a BST&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"output-2\"><span style=\"color: #008000;\">Output:\u00a0<\/span><\/h3>\n<pre>IS BST<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Java program to check if a binary tree is BST or not &#8211; A binary search tree (BST) is a node based binary tree data structure.<\/p>\n","protected":false},"author":1,"featured_media":31620,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,80126,1,2139],"tags":[80573,80564,81149,81143,81142,71207,81174,81173,70290,73814,80574,81180,70657,81144,81151,81185,81182],"class_list":["post-27224","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","category-binary-search-tree","category-coding","category-java","tag-binary-tree-search-java","tag-bst-online","tag-check-if-binary-tree-is-balanced","tag-check-if-binary-tree-is-bst-c","tag-check-if-binary-tree-is-bst-java","tag-examples-of-trees","tag-implement-binary-tree-java","tag-java-code-for-binary-search","tag-java-program-for-binary-search","tag-java-tree","tag-program-of-binary-search-tree","tag-tree-in-data-structure-in-c","tag-tree-java","tag-valid-binary-search-tree","tag-what-is-balanced-binary-tree","tag-what-is-binary-tree-with-example","tag-write-ac-program-to-create-a-binary-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27224","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=27224"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27224\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31620"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27224"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27224"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27224"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}