forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree_Levelorder_Traversal.go
103 lines (87 loc) · 1.56 KB
/
Tree_Levelorder_Traversal.go
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
)
// Queue represents the queue
type Queue struct {
front *QueueNode
rear *QueueNode
size int
}
// QueueNode struct represents the nodes present in the Queue
type QueueNode struct {
Node BinaryTreeNode
next *QueueNode
}
// BinaryTreeNode represents the nodes of the tree
type BinaryTreeNode struct {
data int
left *BinaryTreeNode
right *BinaryTreeNode
}
func (q *Queue) enqueue(n *BinaryTreeNode) {
newNode := QueueNode{
Node: *n,
next: nil,
}
if q.size == 0 {
q.front = &newNode
q.rear = &newNode
} else {
q.rear.next = &newNode
q.rear = q.rear.next
}
q.size++
}
func (q *Queue) dequeue() *BinaryTreeNode {
if q.size == 0 {
return nil
}
n := q.front.Node
q.size--
if q.size > 0 {
q.front = q.front.next
} else {
q.front = nil
q.rear = nil
}
return &n
}
func (q *Queue) isEmpty() bool {
if q.size == 0 {
return true
}
return false
}
func newNode(i int) *BinaryTreeNode {
return &BinaryTreeNode{
data: i,
}
}
// PrintLevelorder prints the Level Order Traversal of the tree
func (nptr *BinaryTreeNode) PrintLevelorder() {
if nptr == nil {
return
}
q := Queue{}
q.enqueue(nptr)
for q.size > 0 {
currentptr := q.dequeue()
if currentptr.left != nil {
q.enqueue(currentptr.left)
}
if currentptr.right != nil {
q.enqueue(currentptr.right)
}
fmt.Print(currentptr.data, " ")
}
}
func main() {
root := newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.right = newNode(6)
root.PrintLevelorder()
}