Advertisement
Guest User

BinTreeNode

a guest
Nov 30th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. class BinaryTreeNode:
  2.     def __init__(self, value, parentNode='self', leftChild='none', rightChild='none'):
  3.         self.Value = value
  4.         self.leftChild = leftChild
  5.         self.rightChild = rightChild
  6.  
  7.         if parentNode == 'self':
  8.             self.parent = self
  9.         else:
  10.             self.parent = parentNode
  11.  
  12.     def addChild(self, child):
  13.         #add a child node. working
  14.         if child.Value < self.Value:
  15.             if self.leftChild == 'none':
  16.                 self.leftChild = child
  17.                 child.parent = self
  18.             else:
  19.                 self.leftChild.addChild(child)
  20.         elif child.Value > self.Value:
  21.             if self.rightChild == 'none':
  22.                 self.rightChild = child
  23.                 child.parent = self
  24.             else:
  25.                 self.rightChild.addChild(child)
  26.  
  27.     def findValue(self, value):
  28.         #Performs a binary search for a specified value
  29.         if value == self.Value:
  30.             print("found!")
  31.             return self
  32.         elif value < self.Value:
  33.             if self.leftChild == 'none':
  34.                 print('value not found')
  35.             else:
  36.                 self.leftChild.findValue(value)
  37.         elif value > self.Value:
  38.             if self.rightChild == 'none':
  39.                 print('value not found')
  40.             else:
  41.                 self.rightChild.findValue(value)
  42.  
  43.     def genList(self):
  44.         #recursively generates a sorted list of child node values
  45.         numList = []
  46.         if self.leftChild != 'none':
  47.             numList.extend(self.leftChild.genList())  #error
  48.         numList.extend(list((self.Value,)))
  49.         if self.rightChild != 'none':
  50.             numList.extend(self.rightChild.genList()) #error
  51.         return numList      
  52.  
  53.     def getAncestor(self):
  54.         #find the top node of the tree. working
  55.         if self.parent == self:
  56.             return self
  57.         else:
  58.             return self.parent.getAncestor()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement