Hi everyone, For this problem: <https://leetcode.c...
# getting-started
e
Hi everyone, For this problem: https://leetcode.com/problems/increasing-order-search-tree/, I’m trying to write a Kotlin solution that clearly separates the logic for tree traversal order from the logic for building the resulting linked list. I did that in other languages, but I’m struggling to come up with an elegant and gibberish-free Kotlin version that doesn’t feel awkward or verbose. Combined all solutions here https://gist.github.com/Sedose/1d0ee8a6717feeb28a17aaeb4ff89080. Would appreciate any suggestions for making it good looking
I know a regular (eager) collection would be perfectly fine here since the tree is small, but I just want to use a lazy sequence for practice with tree traversal
Ok, turns out we do not even need to use intermediate collection to preserve this separation of the logic for tree traversal order from the logic for building the resulting linked list
Copy code
class Solution {
    fun increasingBST(root: TreeNode?): TreeNode? {
        val dummy = TreeNode(0)
        var current = dummy
        
        inorder(root) { node ->
            node.left = null
            current.right = node
            current = node
        }
        
        return dummy.right
    }
    
    private fun inorder(node: TreeNode?, visit: (TreeNode) -> Unit) {
        if (node == null) return
        inorder(node.left, visit)
        visit(node)
        inorder(node.right, visit)
    }
}
y
Nit: I'd make
inorder
tailrec so that the recursion on the right is unfolded into a loop.
👍 1
💯 1