{"id":27245,"date":"2018-01-20T20:25:22","date_gmt":"2018-01-20T14:55:22","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27245"},"modified":"2018-01-20T20:25:22","modified_gmt":"2018-01-20T14:55:22","slug":"python-programming-binary-tree-vertical-order-hashmap-based-method","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-binary-tree-vertical-order-hashmap-based-method\/","title":{"rendered":"Python Programming &#8211; Binary Tree in Vertical Order Hashmap based Method"},"content":{"rendered":"<p>Given a binary tree, print it vertically. The following example illustrates vertical order traversal.<span id=\"more-127848\"><\/span><\/p>\n<pre>           1\r\n        \/    \\\r\n       2      3\r\n      \/ \\    \/ \\\r\n     4   5  6   7\r\n             \\   \\\r\n              8   9 \r\n               \r\n\t\t\t  \r\nThe output of print this tree vertically will be:\r\n4\r\n2\r\n1 5 6\r\n3 8\r\n7\r\n9<\/pre>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-27247\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/print-binary-tree-in-vertical-order.png\" alt=\"binary\" width=\"478\" height=\"496\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/print-binary-tree-in-vertical-order.png 478w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/print-binary-tree-in-vertical-order-289x300.png 289w\" sizes=\"(max-width: 478px) 100vw, 478px\" \/><\/p>\n<p>We have discussed a O(n<sup>2<\/sup>) solution in the <a href=\"http:\/\/www.geeksforgeeks.org\/print-binary-tree-vertical-order\/\" target=\"_blank\" rel=\"noopener noreferrer\">previous post<\/a>. In this post, an efficient solution based on hash map is discussed. We need to check the Horizontal Distances from root for all nodes. If two nodes have the same Horizontal Distance (HD), then they are on same vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1 horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2 is -1, HD for 5 and 6 is 0 and HD for node 7 is +2.<br \/>\nWe can do preorder traversal of the given Binary Tree.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>While traversing the tree, we can recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1. For every HD value, we maintain a list of nodes in a hasp map. Whenever we see a node in traversal, we go to the hash map entry and add the node to the hash map using HD as a key in map.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Python Program<\/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 for printing vertical order of a given<br\/># binary tree<br\/> <br\/># A binary tree node<br\/>class Node:<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\/># Utility function to store vertical order in map &#039;m&#039; <br\/># &#039;hd&#039; is horizontal distance of current node from root<br\/># &#039;hd&#039; is initially passed as 0<br\/>def getVerticalOrder(root, hd, m):<br\/> <br\/>    # Base Case<br\/>    if root is None:<br\/>        return<br\/>     <br\/>    # Store current node in map &#039;m&#039;<br\/>    try:<br\/>        m[hd].append(root.key)<br\/>    except:<br\/>        m[hd] = [root.key]<br\/>     <br\/>    # Store nodes in left subtree<br\/>    getVerticalOrder(root.left, hd-1, m)<br\/>     <br\/>    # Store nodes in right subtree<br\/>    getVerticalOrder(root.right, hd+1, m)<br\/> <br\/># The main function to print vertical order of a binary<br\/>#tree ith given root<br\/>def printVerticalOrder(root):<br\/>     <br\/>    # Create a map and store vertical order in map using<br\/>    # function getVerticalORder()<br\/>    m = dict()<br\/>    hd = 0<br\/>    getVerticalOrder(root, hd, m)<br\/>     <br\/>    # Traverse the map and print nodes at every horizontal<br\/>    # distance (hd)<br\/>    for index, value in enumerate(sorted(m)):<br\/>        for i in m[value]:<br\/>            print i,<br\/>        print<br\/> <br\/> <br\/># Driver program to test above function<br\/>root = Node(1)<br\/>root.left = Node(2)<br\/>root.right = Node(3)<br\/>root.left.left = Node(4)<br\/>root.left.right = Node(5)<br\/>root.right.left = Node(6)<br\/>root.right.right = Node(7)<br\/>root.right.left.right = Node(8)<br\/>root.right.right.right = Node(9)<br\/>print &quot;Vertical order traversal is&quot;<br\/>printVerticalOrder(root)<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Vertical order traversal is\r\n4\r\n2\r\n1 5 6\r\n3 8\r\n7\r\n9<\/pre>\n<p><strong>Time Complexity<\/strong> of hashing based solution can be considered as O(n) under the assumption that we have good hashing function that allows insertion and retrieval operations in O(1) time. In the above C++ implementation, <a href=\"http:\/\/www.cplusplus.com\/reference\/map\/map\/\" target=\"_blank\" rel=\"noopener noreferrer\">map of STL<\/a> is used. map in STL is typically implemented using a Self-Balancing Binary Search Tree where all operations take O(Logn) time. Therefore time complexity of above implementation is O(nLogn).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Note that the above solution may print nodes in same vertical order as they appear in tree.<\/strong> For example, the above program prints 12 before 9. See <a href=\"http:\/\/code.geeksforgeeks.org\/TPyOLR\" target=\"_blank\" rel=\"noopener\">this<\/a> for a sample run.<\/p>\n<pre>             1\r\n          \/     \\\r\n         2       3\r\n        \/  \\    \/  \\\r\n       4    5  6    7\r\n                \\  \/  \\\r\n                 8 10  9 \r\n                     \\\r\n                     11\r\n                       \\\r\n                        12<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>An efficient solution based on hash map is discussed. We need to check the Horizontal Distances from root for all nodes and two nodes have the same<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,80128,4148],"tags":[73309,70268,70285,80816,81249,81253,81252,81250,81255,81251,80798,81254,73910],"class_list":["post-27245","post","type-post","status-publish","format-standard","hentry","category-coding","category-hashing","category-python","tag-binary-search-tree-traversal","tag-binary-tree","tag-binary-tree-traversal","tag-inorder-traversal","tag-pollution-under-control-certificate-wikipedia","tag-postal-order","tag-print-order","tag-sonicwall","tag-traversal-of-tree","tag-tree-drawing","tag-tree-traversal-in-data-structure","tag-vertical-column","tag-what-is-backtracking"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27245","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\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27245"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27245\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}