-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_child.py
More file actions
69 lines (55 loc) · 1.66 KB
/
Copy pathtwo_child.py
File metadata and controls
69 lines (55 loc) · 1.66 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
class Node():
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self,root):
self.root = Node(root)
def two_child_counter(self,node, counter=0):
if not node:
return 0
result = 0
if node.left and node.right:
result += 1
result += (self.two_child_counter(node.left) + self.two_child_counter(node.right))
return result
def insertion(self,tree,n):
if n == tree.value:
return
if n < tree.value:
if tree.left:
self.insertion(tree.left, n)
else:
tree.left = Node(n)
if n > tree.value:
if tree.right:
self.insertion(tree.right, n)
else:
tree.right = Node(n)
def printer(self,type):
if type == "postorder":
return self.postorder(tree.root, "postorder traversal --> ")
def postorder(self,start,traversal):
# L R N
if start:
traversal = self.postorder(start.left,traversal)
traversal = self.postorder(start.right,traversal)
traversal += (str(start.value) + "--")
return traversal
tree = BinaryTree(5)
# tree.insertion(tree.root, 3)
#
# tree.insertion(tree.root, 2)
#
# tree.insertion(tree.root, 99)
#
# tree.insertion(tree.root, 999999)
tree.root.left = Node(1)
tree.root.right = Node(2)
tree.root.left.left = Node(4)
tree.root.left.right = Node(8)
tree.root.right.right = Node(8)
tree.root.right.left = Node(8)
print(tree.printer("postorder"))
print(tree.two_child_counter(tree.root))