class TreeNode:
def __init__(self,v):
self.v=v # A number from the original list
self.nGreater=0 # The number of higher numbers we've seen.
self.lowerChild=None
self.greaterChild=None
def addNode(self,newV):
if newV<self.v:
if self.lowerChild is None:
# New number is lower than this node and we have not seen any such numbers before. Return 1 (this node) plus how many greater-than-this-node children
self.lowerChild=TreeNode(newV)
return 1+self.nGreater
else:
# New number is lower than this node. Return 1 (this node) plus how many greater-than-this-node children plus anything between the new node and this node
return 1+self.nGreater+self.lowerChild.addNode(newV)
else:
self.nGreater+=1
if self.greaterChild is None:
# Greater than this node and we haven't seen such a number before - return that there are no larger numbers below this node
self.greaterChild=TreeNode(newV)
return 0
else:
# Greater than this node - return how many greater-than-the-new-node values are found in the subtree
return self.greaterChild.addNode(newV)
def printTree(self):
chstr=""
if self.lowerChild is None:
chstr+="-"
else:
chstr+=str(self.lowerChild.v)
if self.greaterChild is None:
chstr+=" -"
else:
chstr+=" "+str(self.greaterChild.v)
print "Node:",self.v," Children:",chstr
if self.lowerChild is not None:
self.lowerChild.printTree()
if self.greaterChild is not None:
self.greaterChild.printTree()
a=[5,2,3,1,4]
rootNode=TreeNode(a[0])
b=[0]
for a_i in a[1:]:
b.append(rootNode.addNode(a_i))
print b
rootNode.printTree()