forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Tree_Preorder_Traversal.kt (jainaman224#2585)
* Create Tree_Preorder_Traversal.kt * Update Tree_Preorder_Traversal.kt Taking dynamic input
- Loading branch information
1 parent
412de13
commit 8a48be5
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import java.util.* | ||
class Node<Int>( | ||
var key:Int, | ||
var left:Node<Int>? = null, | ||
var right:Node<Int>? = null | ||
) | ||
{ | ||
fun preorderTraversal() | ||
{ | ||
print("$key ") | ||
left?.preorderTraversal() | ||
right?.preorderTraversal() | ||
} | ||
} | ||
|
||
fun main() { | ||
var read = Scanner(System.`in`) | ||
println("Enter the size of Array:") | ||
val arrSize = read.nextLine().toInt() | ||
var arr = IntArray(arrSize) | ||
val nodes = mutableListOf<Node<Int>>() | ||
println("Enter the array respresentaion of binary tree") | ||
for(i in 0 until arrSize) | ||
{ | ||
arr[i] = read.nextLine().toInt() | ||
nodes.add(Node(arr[i])) | ||
} | ||
for(i in 0..arrSize-2) | ||
{ | ||
if((i*2)+1<arrSize && arr[(i*2)+1]!=-1) | ||
nodes[i].left = nodes[(i*2)+1] | ||
if((i*2)+2<arrSize && arr[(i*2)+2]!=-1) | ||
nodes[i].right = nodes[(i*2)+2] | ||
} | ||
print("Pre Order traversal of tree is ") | ||
nodes[0].preorderTraversal() | ||
} | ||
/* | ||
*Enter the size of Array: | ||
*7 | ||
*Enter the array respresentaion of binary tree | ||
*1 | ||
*2 | ||
*3 | ||
*4 | ||
*5 | ||
*-1 | ||
*7 | ||
*Pre Order traversal of tree is 1 2 4 5 3 7 | ||
*/ |