-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
75 lines (65 loc) · 2.2 KB
/
node.py
File metadata and controls
75 lines (65 loc) · 2.2 KB
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
class Node:
"""
node of formula in tree representation
"""
def __init__(self, t):
self.satisfying_states: set[int] = set()
self.node_count = 0
self.t = t
self.type = t[0]
self.length = len(t)
self.child = None
self.left = None
self.right = None
if self.length == 2:
self.child = Node(t[1]) if isinstance(t[1], (tuple)) else t[1]
elif self.length == 3:
self.left = Node(t[1]) if isinstance(t[1], (tuple)) else t[1]
self.right = Node(t[2]) if isinstance(t[2], (tuple)) else t[2]
self.set_node_count()
def set_node_count(self):
"""
count no of nodes in the descendent trees and set in node_count
"""
if self.length == 2:
self.node_count = 1 + (
self.child.node_count
if isinstance(self.child, Node)
else (1 if isinstance(self.child, str) else 0)
)
else:
self.node_count = (
1
+ (
self.left.node_count
if isinstance(self.left, Node)
else (1 if isinstance(self.left, str) else 0)
)
+ (
self.right.node_count
if isinstance(self.right, Node)
else (1 if isinstance(self.right, str) else 0)
)
)
def inorder_traversal(self):
"""
given a node, print its inorder traversal
a node's child/left/right could be node or string.
"""
print(self.type)
if self.length == 2:
if isinstance(self.child, Node):
self.child.inorder_traversal()
elif self.child is not None:
print(self.child)
else:
if isinstance(self.left, Node):
self.left.inorder_traversal()
elif self.left is not None:
print(self.left)
if isinstance(self.right, Node):
self.right.inorder_traversal()
elif self.right is not None:
print(self.right)
def show(self):
print(self.t)