{"id":27091,"date":"2018-01-03T21:20:30","date_gmt":"2018-01-03T15:50:30","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27091"},"modified":"2018-10-31T15:24:40","modified_gmt":"2018-10-31T09:54:40","slug":"python-programming-inorder-predecessor-successor-given-key-bst","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-inorder-predecessor-successor-given-key-bst\/","title":{"rendered":"Inorder predecessor and successor for a given key in BST"},"content":{"rendered":"<p><strong><span style=\"color: #003366;\">Inorder predecessor and successor for a given key in BST<\/span><\/strong><\/p>\n<p>I recently encountered with a question in an interview at <a href=\"https:\/\/www.wikitechy.com\/top10\/most-popular-ebusiness-websites\" target=\"_blank\" rel=\"noopener\">e-commerce<\/a> company. The interviewer asked the following question:<\/p>\n<p>There is <a href=\"https:\/\/www.wikitechy.com\/technology\/python-program-check-binary-tree-bst-not\/\" target=\"_blank\" rel=\"noopener\">BST<\/a> given with root node with key part as <a href=\"https:\/\/www.wikitechy.com\/forum\/d\/1155-solved-python-integer-incrementing-with\" target=\"_blank\" rel=\"noopener\">integer<\/a> only. The <a href=\"https:\/\/www.wikitechy.com\/tutorials\/c++\/c++-struct\" target=\"_blank\" rel=\"noopener\">structure<\/a> of each node is as follows:<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">struct Node<br\/>{<br\/>    int key;<br\/>    struct Node *left, *right ;<br\/>};<\/code><\/pre> <\/div>\n<p>You need to find the <a href=\"https:\/\/www.wikitechy.com\/technology\/python-program-inorder-successor-binary-search-tree\/\" target=\"_blank\" rel=\"noopener\">inorder successor<\/a> and predecessor of a given key. In case the given key is not found in BST, then return the two values within which this key will lie.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-31786\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2018\/01\/inorder-successor-and-inorder-predecessor.png\" alt=\"inorder successor and inorder predecessor\" width=\"288\" height=\"258\" \/><\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Following is the algorithm to reach the desired result. Its a recursive method:<\/strong><\/p>\n<pre>Input: root node, key\r\noutput: predecessor node, successor node\r\n\r\n1. If root is NULL\r\n      then return\r\n2. if key is found then\r\n    a. If its left subtree is not null\r\n        Then predecessor will be the right most \r\n        child of left subtree or left child itself.\r\n    b. If its right subtree is not null\r\n        The successor will be the left most child \r\n        of right subtree or right child itself.\r\n    return\r\n3. If key is smaller then root node\r\n        set the successor as root\r\n        search recursively into left subtree\r\n    else\r\n        set the predecessor as root\r\n        search recursively into right subtree\r\n\r\n<\/pre>\n<h3 id=\"implementation-of-python-code\"><span style=\"color: #333300;\">Implementation of Python code:<\/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 find predecessor and successor in a BST<br\/> <br\/># A BST node<br\/>class Node:<br\/> <br\/>    # Constructor to create a new node<br\/>    def __init__(self, key):<br\/>        self.key  = key<br\/>        self.left = None<br\/>        self.right = None<br\/> <br\/># This fucntion finds predecessor and successor of key in BST<br\/># It sets pre and suc as predecessor and successor respectively<br\/>def findPreSuc(root, key):<br\/> <br\/>    # Base Case<br\/>    if root is None:<br\/>        return<br\/> <br\/>    # If key is present at root<br\/>    if root.key == key:<br\/> <br\/>        # the maximum value in left subtree is predecessor<br\/>        if root.left is not None:<br\/>            tmp = root.left <br\/>            while(tmp.right):<br\/>                tmp = tmp.right <br\/>            findPreSuc.pre = tmp<br\/> <br\/> <br\/>        # the minimum value in right subtree is successor<br\/>        if root.right is not None:<br\/>            tmp = root.right<br\/>            while(temp.left):<br\/>                tmp = tmp.left <br\/>            findPreSuc.suc = tmp <br\/> <br\/>        return<br\/> <br\/>    # If key is smaller than root&#039;s key, go to left subtree<br\/>    if root.key &gt; key :<br\/>        findPreSuc.suc = root <br\/>        findPreSuc(root.left, key)<br\/> <br\/>    else: # go to right subtree<br\/>        findPreSuc.pre = root<br\/>        findPreSuc(root.right, key)<br\/> <br\/># A utility function to insert a new node in with given key in BST<br\/>def insert(node , key):<br\/>    if node is None:<br\/>        return Node(key)<br\/> <br\/>    if key &lt; node.key:<br\/>        node.left = insert(node.left, key)<br\/> <br\/>    else:<br\/>        node.right = insert(node.right, key)<br\/> <br\/>    return node<br\/> <br\/> <br\/># Driver program to test above function<br\/>key = 65 #Key to be searched in BST<br\/>  <br\/>&quot;&quot;&quot; Let us create following BST<br\/>              50<br\/>           \/     \\<br\/>          30      70<br\/>         \/  \\    \/  \\<br\/>       20   40  60   80 <br\/>&quot;&quot;&quot;<br\/>root = None<br\/>root = insert(root, 50)<br\/>insert(root, 30);<br\/>insert(root, 20);<br\/>insert(root, 40);<br\/>insert(root, 70);<br\/>insert(root, 60);<br\/>insert(root, 80);<br\/> <br\/># Static variables of the function findPreSuc <br\/>findPreSuc.pre = None<br\/>findPreSuc.suc = None<br\/> <br\/>findPreSuc(root, key)<br\/> <br\/>if findPreSuc.pre is not None:<br\/>    print &quot;Predecessor is&quot;, findPreSuc.pre.key<br\/> <br\/>else:<br\/>    print &quot;No Predecessor&quot;<br\/> <br\/>if findPreSuc.suc is not None:<br\/>    print &quot;Successor is&quot;, findPreSuc.suc.key<br\/>else:<br\/>    print &quot;No Successor&quot;<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h3 id=\"output\"><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre>Predecessor is 60\r\nSuccessor is 70<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>python Programming Inorder predecessor and successor for a given key in BST &#8211; I recently encountered with a question in an interview at e-commerce company.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80126,1,4148],"tags":[70284,70277,80563,80542,80821,73310,72694,73309,80819,80551,80557,80820,80567,70268,80537,80548,80816,80574,80813,80541,70280,80817,80814],"class_list":["post-27091","post","type-post","status-publish","format-standard","hentry","category-binary-search-tree","category-coding","category-python","tag-binary-search-tree-in-data-structure","tag-binary-search-tree-java","tag-binary-search-tree-java-example-code","tag-binary-search-tree-pdf","tag-binary-search-tree-ppt","tag-binary-search-tree-program-in-c","tag-binary-search-tree-program-in-data-structure-using-c","tag-binary-search-tree-traversal","tag-binary-search-tree-traversal-example","tag-binary-search-tree-traversal-inorder-preorder-postorder-example","tag-binary-search-tree-with-example","tag-binary-search-trees-pdf","tag-binary-search-trees-ppt","tag-binary-tree","tag-binary-tree-algorithm-in-data-structure","tag-definition-of-binary-search-tree","tag-inorder-traversal","tag-program-of-binary-search-tree","tag-program-to-create-a-binary-tree","tag-root-binary","tag-search-tree","tag-threaded-binary-tree","tag-threaded-binary-tree-in-data-structure"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27091","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=27091"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27091\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27091"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27091"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27091"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}