-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTree.py
More file actions
63 lines (53 loc) · 1.5 KB
/
BinaryTree.py
File metadata and controls
63 lines (53 loc) · 1.5 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
import time
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if self.data > data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.data < data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data),
if self.right:
self.right.PrintTree()
def traverse(self, root):
result = []
if root:
result = self.traverse(root.left)
result.append(root.data)
result = result + self.traverse(root.right)
return result
def preorder(self, root):
result = []
if root:
result.append(root.data)
result += self.preorder(root.left)
result += self.preorder(root.right)
return result
def postorder(self, root):
result = []
if root:
result = self.postorder(root.left)
result += self.postorder(root.right)
result.append(root.data)
return result
root = Node(5)
root.insert(10)
root.insert(2)
root.insert(1)
root.insert(4)
root.insert(11)
root.insert(12)
print(root.postorder(root))