forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree_Levelorder_Traversal.kt
104 lines (94 loc) · 1.92 KB
/
Tree_Levelorder_Traversal.kt
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
// Code for printing Level Order of Tree in Kotlin
class Node
{
//Structure of Binary tree node
int num;
Node left, right;
public Node(int num)
{
key = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
BinaryTree()
{
root = null;
}
//function to print level order traversal
fun printLevelOrder():void
{
int h = height(root);
int i;
// To Print nodes at each level
for (i = 1; i <= h; i++)
{
printGivenLevel(root, i);
}
}
//Function to calculate height of Tree
fun height(Node: root):void
{
if (root == null)
{
return 0;
}
else
{
// compute height of each subtree
int lheight = height(root.left);
int rheight = height(root.right);
// use the larger one
if (lheight > rheight)
{
return(lheight + 1);
}
else
{
return(rheight + 1);
}
}
}
fun printGivenLevel(Node:root ,int: level):void
{
if (root == null)
{
return;
}
//Print data
if (level == 1)
{
println(root.data);
}
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}
fun main()
{
BinaryTree tree = new BinaryTree();
var read = Scanner(System.`in`)
println("Enter the size of Array:")
val arrSize = read.nextLine().toInt()
var arr = IntArray(arrSize)
println("Enter data of binary tree")
for(i in 0 until arrSize)
{
arr[i] = read.nextLine().toInt()
tree.root = new Node(arr[i]);
}
println("Level order traversal of binary tree is ");
tree.printLevelOrder();
}
}
/*
Input:
1 2 3 4 5 6 7 8 9
Output:
Level order traversal of binary tree is
1 2 3 4 5 6 7 8 9
*/