LeetCode in Kotlin

144. Binary Tree Preorder Traversal

Easy

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1:

Input: root = [1,null,2,3]

Output: [1,2,3]

Example 2:

Input: root = []

Output: []

Example 3:

Input: root = [1]

Output: [1]

Constraints:

Follow up: Recursive solution is trivial, could you do it iteratively?

Solution

import com_github_leetcode.TreeNode

/*
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    fun preorderTraversal(root: TreeNode?): List<Int> {
        val result: MutableList<Int> = ArrayList()
        if (root == null) {
            return result
        }
        val stack: ArrayDeque<TreeNode?> = ArrayDeque()
        var current: TreeNode? = root
        while (current != null || stack.isNotEmpty()) {
            while (current != null) {
                result.add(current.`val`)
                stack.addLast(current.right)
                current = current.left
            }
            current = stack.removeLast()
        }
        return result
    }
}