-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree.py
More file actions
57 lines (49 loc) · 1.35 KB
/
Binary_Tree.py
File metadata and controls
57 lines (49 loc) · 1.35 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
class Binary_Tree:
def __init__(self,val):
self.value = val
self.left = None
self.right = None
def preorder(self,root):
if root:
print(root.value,end = ' ')
self.preorder(root.left)
self.preorder(root.right)
def inorder(self,root):
if root:
self.inorder(root.left)
print(root.value, end = ' ')
self.inorder(root.right)
def postorder(self, root):
if root:
self.postorder(root.left)
self.postorder(root.right)
print(root.value, end = ' ')
def depth(self, root):
if root == None:
return 0
else:
l_depth = self.depth(root.left)
r_depth = self.depth(root.right)
depth_value = max(l_depth,r_depth)+1
return depth_value
def count(self, root):
if root == None:
return 0
else:
l_count = self.count(root.left)
r_count = self.count(root.right)
return (1+l_count+r_count)
# Driver Code
root = Binary_Tree(1)
root.left = Binary_Tree(2)
root.right = Binary_Tree(3)
root.left.left = Binary_Tree(4)
root.left.right = Binary_Tree(5)
root.right.left = Binary_Tree(6)
print("Preorder Traversal of Tree: ")
print(root.preorder(root))
print("Inorder Traversal of Tree: ")
print(root.inorder(root))
print("Postorder Traversal of Tree: ")
print(root.postorder(root))
print("Postorder Traversal of Tree: {}".format(root.depth(root)))