forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inorder_traversal_binarytree.go
106 lines (82 loc) · 1.69 KB
/
inorder_traversal_binarytree.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
104
105
package main
import (
"fmt"
"os"
)
//Node defines the structure of a particular node in binary tree
type Node struct {
data int
left *Node
right *Node
}
//NewNode creates a node and returns it's pointer
func NewNode(data int) *Node {
return &Node{
data: data,
}
}
//CreateTree creates a new tree from level order array
func (root *Node) CreateTree(arr []int, pos, size int) *Node {
var r *Node // nill by default
if pos < size {
r = NewNode(arr[pos])
//fill left subtree
r.left = r.CreateTree(arr, pos*2+1, size)
//fill right subtree
r.right = r.CreateTree(arr, pos*2+2, size)
}
return r
}
//InorderTraversal prints the Inorder traversal of tree
func (root *Node) InorderTraversal() {
//Inorder Traversal : Left -> Root -> Right
if root != nil {
root.left.InorderTraversal()
fmt.Printf("%v ", root.data)
root.right.InorderTraversal()
}
}
//Driver Code
func main() {
//taking size of tree
var size int
fmt.Println("Enter size of the tree: ")
_, err := fmt.Scanf("%d\n", &size)
//exit on invalid size
if err != nil {
println("Invalid size")
os.Exit(-1)
}
//allocating memory for array
arr := make([]int, size)
fmt.Println("Enter values in level order fashion: ")
//Taking inpur
for i := 0; i < size; i++ {
_, err = fmt.Scanf("%d", &arr[i])
if err != nil {
println("Invalid argument")
os.Exit(-1)
}
}
//declaring root
var root *Node
//creating the tree
root = root.CreateTree(arr, 0, size)
//Calling InorderTraversal
root.InorderTraversal()
}
/*
Sample input:
Enter size of the tree:
6
Enter values in level order fashion:
5 6 7 3 10 9
Example Input Tree
5
/ \
6 7
/ \ /
3 10 9
Output
3 6 10 5 9 7
*/