Advertisement
DMG

Trie

DMG
Jun 5th, 2014
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None | 0 0
  1. __author__ = 'DMG'
  2.  
  3. from Red import Queue
  4.  
  5. class TreeNode(object):
  6.     def __init__(self, data):
  7.         self._data = data
  8.         self._parent = None
  9.         self._children = []
  10.         self._indexes = []
  11.  
  12.     def isLeaf(self):
  13.         return self._children is None
  14.  
  15.     def isRoot(self):
  16.         return self._parent is None
  17.  
  18.     def addChild(self, n):
  19.         n._parent = self
  20.         self._children.append(n)
  21.  
  22. class Trie(object):
  23.     def __init__(self):
  24.         self._root = None
  25.  
  26.     def isEmpty(self):
  27.         return self._root is None
  28.  
  29.     def preorder(self, node):
  30.         if not self.isEmpty():
  31.             print node._data,
  32.             for c in node._children:
  33.                 self.preorder(c)
  34.  
  35.     def postorder(self, node):
  36.         if not self.isEmpty():
  37.             for c in node._children:
  38.                 self.postorder(c)
  39.             print node._data
  40.  
  41.     def breadthFirst(self):
  42.         if not self.isEmpty():
  43.             q = Queue()
  44.             q.enQueue(self._root)
  45.  
  46.             while not q.isEmpty():
  47.                 e = q.deQueue()
  48.                 print e._data,
  49.                 for c in e._children:
  50.                     q.enQueue(c)
  51.  
  52.     # Feeling proud and stupid
  53.     def addWord(self, node, string):
  54.         if len(string) > 0:
  55.             for c in node._children:
  56.                 if c._data == string[0]:
  57.                     self.addWord(c, string[1:])
  58.                     return
  59.  
  60.         while len(string) > 0:
  61.             currentNode = TreeNode(string[0])
  62.             node.addChild(currentNode)
  63.             node = currentNode
  64.             string = string[1:]
  65.  
  66.  
  67.  
  68. trie = Trie()
  69. trie._root = TreeNode(" ")
  70.  
  71. listaRijeci = ["bear", "sell", "stop", "stock", "bid", "bell", "buy"]
  72.  
  73. for rijec in listaRijeci:
  74.     trie.addWord(trie._root, rijec)
  75.  
  76. trie.breadthFirst()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement