JavaScript
x
25
25
1
# Binary tree node
2
class node:
3
4
def __init__(self, data):
5
self.left=None
6
self.right=None
7
self.data=data
8
9
# Function to create a new
10
# Binary node
11
def newNode(data):
12
return node(data)
13
14
def t():
15
root=newNode("A")
16
root.left = newNode("B")
17
root.right = newNode("C")
18
root.left.left = newNode("D")
19
root.left.right = newNode("G")
20
root.right.right = newNode("E")
21
root.right.right.left = newNode("F")
22
23
24
print(t)
25
Hi, I have tried to create a Binary Tree above but I did not managed to print out the binary tree when I print “t”.
Instead of a Binary Tree, it shows me this:
Advertisement
Answer
Function t
just creates a binary tree. If you want to print a tree you need to traverse it and print it. Depending on the way you want to print a tree, there are different traversal techniques, the popular of which are Inorder
, Preorder
and Postorder
. Check this wiki link for tree traversal methods.
Your code has to be extended to do the required tree traversal. Sample is below:
JavaScript
1
52
52
1
# Binary tree node
2
class node:
3
4
def __init__(self, data):
5
self.left=None
6
self.right=None
7
self.data=data
8
9
# Function to create a new
10
# Binary node
11
def newNode(data):
12
return node(data)
13
14
def t():
15
root=newNode("A")
16
root.left = newNode("B")
17
root.right = newNode("C")
18
root.left.left = newNode("D")
19
root.left.right = newNode("G")
20
root.right.right = newNode("E")
21
root.right.right.left = newNode("F")
22
return root
23
24
25
def in_order(root):
26
if root:
27
in_order(root.left)
28
print (root.data)
29
in_order(root.right)
30
31
def pre_order(root):
32
if root:
33
print (root.data)
34
pre_order(root.left)
35
pre_order(root.right)
36
37
def post_order(root):
38
if root:
39
post_order(root.left)
40
post_order(root.right)
41
print (root.data)
42
43
root = t()
44
45
46
print ("In Order")
47
in_order(root)
48
print ("Pre Order")
49
pre_order(root)
50
print ("Post Order")
51
post_order(root)
52
Output:
JavaScript
1
25
25
1
In Order
2
D
3
B
4
G
5
A
6
C
7
F
8
E
9
Pre Order
10
A
11
B
12
D
13
G
14
C
15
E
16
F
17
Post Order
18
D
19
G
20
B
21
F
22
E
23
C
24
A
25