-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathbinaryTree.py
80 lines (65 loc) · 1.77 KB
/
binaryTree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
''' mbinary
#########################################################################
# File : sort.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-07-05 17:18
# Description:
#########################################################################
'''
from functools import total_ordering
@total_ordering
class node:
def __init__(self, val, left=None, right=None):
self.val = val
self.frequency = 1
self.left = left
self.right = right
def __lt__(self, x):
return self.val < x.val
def __eq__(self, x):
return self.val == x.val
def inc(self):
self.val += 1
def dec(self):
self.val -= 1
def incFreq(self):
self.frequency += 1
def decFreq(self):
self.frequency -= 1
class binaryTree:
def __init__(self, reverse=True):
self.reverse = reverse
self.data = None
def cmp(self, n1, n2):
ret = 0
if n1 < n2:
ret = -1
if n1 > n2:
ret = 1
return ret * -1 if self.reverse else ret
def addNode(self, nd):
def _add(prt, chd):
if self.cmp(prt, chd) == 0:
prt.incFreq()
return
if self.cmp(prt, chd) < 0:
if not isinstance(nd, node):
nd = node(nd)
if not self.root:
self.root = node(val)
else:
if self.root == val:
self.root.incfreq()
else:
cur = self.root
def build(self, lst):
dic = {}
for i in lst:
if i in dic:
dic[i].incFreq()
else:
dic[i] = node(i)
self.data = list(dic.values())