Advertisement
Fiszu

Untitled

May 20th, 2020
1,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. class BSTNode:
  2.     def __init__(self,key,value):
  3.         self.key = key
  4.         self.value = value
  5.         self.left = None
  6.         self.right = None
  7.  
  8.     def display(self):
  9.         lines, _, _, _ = self._display_aux()
  10.         for line in lines:
  11.             print(line)
  12.  
  13.     def _display_aux(self):
  14.         """Returns list of strings, width, height, and horizontal coordinate of the root."""
  15.         # No child.
  16.         if self.right is None and self.left is None:
  17.             line = '%s' % self.key
  18.             width = len(line)
  19.             height = 1
  20.             middle = width // 2
  21.             return [line], width, height, middle
  22.  
  23.         # Only left child.
  24.         if self.right is None:
  25.             lines, n, p, x = self.left._display_aux()
  26.             s = '%s' % self.key
  27.             u = len(s)
  28.             first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s
  29.             second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '
  30.             shifted_lines = [line + u * ' ' for line in lines]
  31.             return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2
  32.  
  33.         # Only right child.
  34.         if self.left is None:
  35.             lines, n, p, x = self.right._display_aux()
  36.             s = '%s' % self.key
  37.             u = len(s)
  38.             first_line = s + x * '_' + (n - x) * ' '
  39.             second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '
  40.             shifted_lines = [u * ' ' + line for line in lines]
  41.             return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2
  42.  
  43.         # Two children.
  44.         left, n, p, x = self.left._display_aux()
  45.         right, m, q, y = self.right._display_aux()
  46.         s = '%s' % self.key
  47.         u = len(s)
  48.         first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' '
  49.         second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '
  50.         if p < q:
  51.             left += [n * ' '] * (q - p)
  52.         elif q < p:
  53.             right += [m * ' '] * (p - q)
  54.         zipped_lines = zip(left, right)
  55.         lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines]
  56.         return lines, n + m + u, max(p, q) + 2, n + u // 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement