1class TreeNode:
2 def __init__(self, data):
3 self.data = data
4 self.children = []
5 self.parent = None
6
7 def add_child(self, child):
8 child.parent = self
9 self.children.append(child)
10
11 def getlevel(self):
12 level = 0
13 p = self.parent
14 while p:
15 level += 1
16 p = p.parent
17 return level
18
19 def printt(self):
20 prefix = (" " * 4 * self.getlevel()) + ("|--" if self.parent else "")
21 print(prefix + self.data)
22 if self.children:
23 for child in self.children:
24 child.printt()
25
26
27def build_tree():
28 root = TreeNode("Food")
29
30 italy = TreeNode("Italy")
31 italy.add_child(TreeNode("Pizza"))
32 italy.add_child(TreeNode("Lasgna"))
33 italy.add_child(TreeNode("Pistacho Ice"))
34
35 chinese = TreeNode("Chineese")
36 chinese.add_child(TreeNode("Noodles"))
37 chinese.add_child(TreeNode("Rice balls"))
38 chinese.add_child(TreeNode("Fried Rice"))
39
40 mexican = TreeNode("Mexican")
41 mexican.add_child(TreeNode('Tacos'))
42 mexican.add_child(TreeNode('Gyro'))
43 mexican.add_child(TreeNode('Shawarma'))
44
45 root.add_child(italy)
46 root.add_child(chinese)
47 root.add_child(mexican)
48
49 return root
50
51 # mexican.printt()
52
53
54if __name__ == "__main__":
55 root = build_tree()
56 root.printt()
57
1import random
2class Node:
3 def __init__(self, v, dx=None, sx=None):
4 self.dx = dx
5 self.sx = sx
6 self.v = v
7
8 def nodeCount(self):
9 if self is None:
10 return 0
11 x, y = 0, 0
12 if self.sx:
13 x = self.sx.nodeCount()
14 if self.dx:
15 y = self.dx.nodeCount()
16 return x + y + 1
17
18 def minValue(self):
19 if self is None:
20 return float("+inf")
21 x = y = float("+inf")
22 if self.sx:
23 x = self.sx.minValue()
24 if self.dx:
25 y = self.dx.minValue()
26 return min(self.v, x, y)
27
28 def maxValue(self):
29 if self is None:
30 return float("-inf")
31 x = y = float("-inf")
32 if self.sx:
33 x = self.sx.maxValue()
34 if self.dx:
35 y = self.dx.maxValue()
36 return max(self.v, x, y)
37
38 def printNode(self):
39 if self is None:
40 return
41 print(self.v)
42 if self.sx:
43 self.sx.printNode()
44 if self.dx:
45 self.dx.printNode()
46
47class binaryTree:
48 def __init__(self, Node=None):
49 self.Node = Node
50
51 def buildTree(self, numberOfNode, valueLimit):
52 if numberOfNode == 0:
53 return None
54
55 node = Node(random.randint(1, valueLimit))
56 numberOfNode -= 1
57 if numberOfNode >= 0:
58 x = random.randint(0, numberOfNode)
59 node.sx = self.buildTree(x, valueLimit)
60 node.dx = self.buildTree(numberOfNode-x, valueLimit)
61
62 return node