paint-brush
Kotlin Binary Tree Preorder Traversal (A Recursive Solution and Without Using Recursion)by@okyrcheuskaya
867 reads
867 reads

Kotlin Binary Tree Preorder Traversal (A Recursive Solution and Without Using Recursion)

by Volha KurcheuskayJanuary 20th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Algorithm has a time complexity of O(n), where n is the number of nodes in the tree. It uses a stack to keep track of the nodes that still need to be visited. I apologize for the confusion and for any inconvenience this may have caused. Let me know if you have any other questions.
featured image - Kotlin Binary Tree Preorder Traversal (A Recursive Solution and Without Using Recursion)
Volha Kurcheuskay HackerNoon profile picture


This post is about preorder traversal of a binary tree, a method of traversing the tree in which the current node is visited before its children. The preorder traversal algorithm visits the root node first, then recursively visits the left subtree, followed by the right subtree. The result of a preorder traversal is a list of the nodes' values in the order they are visited. This post will help you to understand how to traverse a binary tree and also how to implement it in different ways.


Preorder traversal is a method of traversing a binary tree where the current node is visited before its children. The algorithm visits the root node first, then recursively visits the left subtree, followed by the right subtree. The result of a preorder traversal is a list of the nodes' values in the order they are visited.


In this problem, you are given the root of a binary tree represented by the TreeNode class in Kotlin, which has a val property for the node's value and left and right properties for its left and right children, respectively. Your task is to write two implementations of a function that performs a preorder traversal of the binary tree and returns a list of the nodes' values. One should be a recursive solution and the other should not use recursion.


Here is the class signature of the function:

fun preorderTraversal(root: TreeNode?): List<Int>


The input to the function is the root node of the binary tree, and the output is a list of integers representing the values of the nodes in the order they are visited during the preorder traversal.


Descriptions:


Given the root of a binary tree, return the preorder traversal of its nodes' values. Do this both with a recursive solution and without using recursion.

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}


Here is a recursive solution to the problem:


fun preorderTraversal(root: TreeNode?): List<Int> {
    val result = mutableListOf<Int>()
    if (root == null) return result
    result.add(root.val)
    result.addAll(preorderTraversal(root.left))
    result.addAll(preorderTraversal(root.right))
    return result
}



This function does a preorder traversal of the binary tree and returns a list of the nodes' values in the order that they are visited.


The algorithm works as follows:

  1. If the root node is null, return an empty list.
  2. Add the root node's value to the result list.
  3. Recursively traverse the left subtree by calling the function on the root's left child and add the returned list to the result list.
  4. Recursively traverse the right subtree by calling the function on the root's right child and add the returned list to the result list.
  5. Return the result list.

This algorithm has a time complexity of O(n), where n is the number of nodes in the tree, and a space complexity of O(h), where h is the height of the tree (due to the call stack).


Here is a solution using an iterative approach (i.e., without using recursion):


fun preorderTraversal(root: TreeNode?): List<Int> {
val result = mutableListOf<Int>()
val stack = Stack<TreeNode>()
var current = root
while (current != null || stack.isNotEmpty()) {
    while (current != null) {
        result.add(current.val)
        stack.push(current)
        current = current.left
    }

    current = stack.pop()
    current = current.right
}
return result
}


This function does a preorder traversal of the binary tree and returns a list of the nodes' values in the order that they are visited. It uses a stack to keep track of the nodes that still need to be visited.


The algorithm works as follows:

  1. Initialize an empty stack and set the current node to the root of the tree.

  2. While the current node is not null or the stack is not empty:

    1. While the current node is not null:

      1. Add the current node's value to the result list.
      2. Push the current node onto the stack.
      3. Set the current node to its left child.
    2. Pop the top node from the stack and set the current node to its right child.

  3. Return the result list.


This algorithm has a time complexity of O(n), where n is the number of nodes in the tree, and a space complexity of O(h), where h is the height of the tree.


I hope this helps! Let me know if you have any other questions.