Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Level Order Traversal in Kotlin #2757

Merged
merged 1 commit into from
Apr 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions Tree_Levelorder_Traversal/Tree_Levelorder_Traversal.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
*/