-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarytree.py
76 lines (66 loc) · 1.69 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
#! /usr/bin
from random import shuffle
from Queue import Queue
numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
shuffle(numbers)
print numbers
print ''
class TreeNode:
def __init__(self, nodeData):
self.data = nodeData
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def insert(self, nodeData, root):
if root == None:
self.root = TreeNode(nodeData)
print 'Root: ' + str(self.root.data)
else:
if nodeData <= root.data:
if root.left == None:
root.left = TreeNode(nodeData)
else:
self.insert(nodeData, root.left)
else:
if root.right == None:
root.right = TreeNode(nodeData)
else:
self.insert(nodeData, root.right)
def depthFirst(self, node):
print str(node.data)
if node.left != None:
self.depthFirst(node.left)
if node.right != None:
self.depthFirst(node.right)
def depth(self, node):
lcount = 0;
rcount = 0;
if node == None:
return 0;
if node.left != None:
lcount = self.depth(node.left)
if node.right != None:
rcount = self.depth(node.right)
return 1 + max(rcount, lcount)
def breadthFirst(self, node):
q = Queue()
q.put(self.root)
while not q.empty():
t = q.get()
print str(t.data)
if t.left != None:
q.put(t.left)
if t.right != None:
q.put(t.right)
tree = Tree()
for n in numbers:
tree.insert(n, tree.root)
print 'Depth: ' + str(tree.depth(tree.root))
print 'Depth-first (preorder) traversal: '
tree.depthFirst(tree.root)
print 'Breadth-first traversal: '
tree.breadthFirst(tree.root)
#tree.printTree()
#print tree.depth(tree.root);