algorithm-in-python/sort/binaryTree.py

81 lines
1.8 KiB
Python
Raw Normal View History

2018-07-08 23:28:29 +08:00
''' mbinary
#########################################################################
# File : sort.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-07-08 23:28:29 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-07-05 17:18
# Description:
#########################################################################
'''
2018-07-08 16:41:55 +08:00
from functools import total_ordering
2020-04-15 12:28:20 +08:00
2018-07-08 16:41:55 +08:00
@total_ordering
class node:
2020-04-15 12:28:20 +08:00
def __init__(self, val, left=None, right=None):
self.val = val
2018-07-08 16:41:55 +08:00
self.frequency = 1
2020-04-15 12:28:20 +08:00
self.left = left
self.right = right
def __lt__(self, x):
return self.val < x.val
def __eq__(self, x):
return self.val == x.val
2018-07-08 16:41:55 +08:00
def inc(self):
2020-04-15 12:28:20 +08:00
self.val += 1
2018-07-08 16:41:55 +08:00
def dec(self):
2020-04-15 12:28:20 +08:00
self.val -= 1
2018-07-08 16:41:55 +08:00
def incFreq(self):
2020-04-15 12:28:20 +08:00
self.frequency += 1
2018-07-08 16:41:55 +08:00
def decFreq(self):
2020-04-15 12:28:20 +08:00
self.frequency -= 1
2018-07-08 16:41:55 +08:00
class binaryTree:
2020-04-15 12:28:20 +08:00
def __init__(self, reverse=True):
2018-07-08 16:41:55 +08:00
self.reverse = reverse
2020-04-15 12:28:20 +08:00
self.data = None
def cmp(self, n1, n2):
ret = 0
if n1 < n2:
ret = -1
if n1 > n2:
ret = 1
2018-07-08 16:41:55 +08:00
return ret * -1 if self.reverse else ret
2020-04-15 12:28:20 +08:00
def addNode(self, nd):
def _add(prt, chd):
if self.cmp(prt, chd) == 0:
2018-07-08 16:41:55 +08:00
prt.incFreq()
return
2020-04-15 12:28:20 +08:00
if self.cmp(prt, chd) < 0:
2018-07-08 16:41:55 +08:00
2020-04-15 12:28:20 +08:00
if not isinstance(nd, node):
nd = node(nd)
if not self.root:
self.root = node(val)
2018-07-08 16:41:55 +08:00
else:
if self.root == val:
self.root.incfreq()
else:
cur = self.root
2020-04-15 12:28:20 +08:00
def build(self, lst):
2018-07-08 16:41:55 +08:00
dic = {}
for i in lst:
if i in dic:
dic[i].incFreq()
else:
dic[i] = node(i)
2020-04-15 12:28:20 +08:00
self.data = list(dic.values())