A binary tree is a tree that includes at most two children, often referred
to as the left and right children:
Kotlin Implementation
class BinaryNode<T>( val value: T, var left: BinaryNode<T>? = null, var right: BinaryNode<T>? = null )
Binary tree traversing
We can traverse the binary tree in three ways.
- pre-order traversal
- in-order traversal
- post-order traversal
Pre-order traversal
In the preorder traversal algorithm, we first visit the root node and then
the left and right node recursively.
kotlin Extention function for pre-order traversal algorithm
fun <T> BinaryNode<T>.preOrder( visit: (BinaryNode<T>) -> Unit) { visit(this) left?.preOrder(visit) right?.preOrder(visit) }
In-order traversal
In order-traversal visit the node in the following order.
- if the current node has a left child, recursively visit it first.
- visit the current node itself
- if the current node has a right child, recursively visit this child.
fun <T> BinaryNode<T>.inOrder( visit: (BinaryNode<T>) -> Unit) { left?.inOrder(visit) visit(this) right?.inOrder(visit) }
Post-order traversal
The post order traversal visits the node in the following order.
- if the current node has a left child, recursively visit this child first.
- if the current node has the right child, recursively visit this child.
- visit the node itself
fun <T> BinaryNode<T>.postOrder(visit: (BinaryNode<T>) -> Unit) { left?.postOrder(visit) right?.postOrder(visit) visit(this) }
let's create a tree and traverse it with all three functions
fun main() { val one = BinaryNode(1) val two = BinaryNode(2) val three = BinaryNode(3) val four = BinaryNode(4) val five = BinaryNode(5) val six = BinaryNode(6) one.left = two one.right = three two.left = four two.right = five three.right = six println("Pre order traversal: ") one.preOrder { print(it.value.toString() + ", ") } println("nIn order traversal: ") one.inOrder { print(it.value.toString() + ", ") } println("nPost order traversal") one.postOrder { print(it.value.toString() + ", ") } }
Output
Pre order traversal: 1, 2, 4, 5, 3, 6, In order traversal: 4, 2, 5, 1, 3, 6, Post order traversal 4, 5, 2, 6, 3, 1,