SHOW:
|
|
- or go back to the newest paste.
1 | class BinaryTreeNode: | |
2 | - | def __init__(self, value, parentNode='self', leftChild='none', rightChild='none'): |
2 | + | def __init__(self, value, parentNode=None, leftChild=None, rightChild=None): |
3 | self.Value = value | |
4 | self.leftChild = leftChild | |
5 | self.rightChild = rightChild | |
6 | ||
7 | - | if parentNode == 'self': |
7 | + | if parentNode is None: |
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': |
15 | + | if self.leftChild is 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': |
21 | + | if self.rightChild is 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': |
33 | + | if self.leftChild is None: |
34 | print('value not found') | |
35 | else: | |
36 | self.leftChild.findValue(value) | |
37 | elif value > self.Value: | |
38 | - | if self.rightChild == 'none': |
38 | + | if self.rightChild is None: |
39 | print('value not found') | |
40 | else: | |
41 | self.rightChild.findValue(value) | |
42 | ||
43 | - | def genList(self): |
43 | + | def genList(self, numList=None): |
44 | #recursively generates a sorted list of child node values | |
45 | - | numList = [] |
45 | + | if numList is None: |
46 | - | if self.leftChild != 'none': |
46 | + | numList = [] |
47 | - | numList.extend(self.leftChild.genList()) #error |
47 | + | if self.leftChild is not None: |
48 | - | numList.extend(list((self.Value,))) |
48 | + | self.leftChild.genList(numList) |
49 | - | if self.rightChild != 'none': |
49 | + | numList.append(self.Value) |
50 | - | numList.extend(self.rightChild.genList()) #error |
50 | + | if self.rightChild is not None: |
51 | self.rightChild.genList(numList) | |
52 | return numList | |
53 | ||
54 | def getAncestor(self): | |
55 | - | if self.parent == self: |
55 | + | |
56 | if self.parent is self: | |
57 | return self | |
58 | else: | |
59 | return self.parent.getAncestor() |