LeetCode – 144. Binary Tree Preorder Traversal

題目連結: https://leetcode.com/problems/binary-tree-preorder-traversal/

Iterative version:

func preorderTraversal(_ root: TreeNode?) -> [Int] {
    guard let root = root else { return [] }
    var stack: [TreeNode] = [root]
    var arr: [Int] = []
    while !stack.isEmpty {
        let last = stack.removeLast()
        arr.append(last.val)
        if let right = last.right {
            stack.append(right)
        }
        if let left = last.left {
            stack.append(left)
        }
    }
    return arr
}

Recursive version 1:

func preorderTraversal(_ root: TreeNode?) -> [Int] {
    guard let root = root else {
        return []
    }
    var arr = [Int]()
    helper(root, arr: &arr)
    return arr
}

func helper(_ root: TreeNode?, arr: inout [Int]) {
    guard let root = root else { return }
    arr.append(root.val)
    helper(root.left, arr: &arr)
    helper(root.right, arr: &arr)
}

Recursive version 2:

func preorderTraversal(_ root: TreeNode?) -> [Int] {
    guard let root = root else { return [] }
    return [root.val] + preorderTraversal(root.left) + preorderTraversal(root.right)
}

Ref: https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/1396541/Swift-oror-Easy-Recursion