Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 1.05 KB

leetcode_144.md

File metadata and controls

37 lines (29 loc) · 1.05 KB

LeetCode Problems

144. Binary Tree Preorder Traversal

class Solution {
    fun preorderTraversal(root: TreeNode?): List<Int> {
        val result = mutableListOf<Int>()
        optimizedDFS(root, result)
        return result
    }
    /*
        For memory efficient, use one MutableList to contain each node's `val`.
        List-initialization like `listOf()` on each steps is memory-unefficient like below straight-forward solution.
        fun dfs(root: TreeNode?): List<Int> {
            return listOf(root.`val` ?: return) + dfs(root.left) + dfs(root.right)
        }
     */
    fun optimizedDFS(root: TreeNode?, list: MutableList<Int>) {
        root ?: return
        list.add(root.`val`)
        // preorder traversal, iterate all left -> right bottom-up 
        optimizedDFS(root.left, list)
        optimizedDFS(root.right, list)
    }
}