```
class Solution {
func preorderTraversal(_ root: TreeNode?) -> [Int] {
guard let root = root else {
return []
}
var result = [Int]()
var stack = [TreeNode]()
stack.append(root)
while !stack.isEmpty {
let node = stack.removeLast()
result.append(node.val)
if let rightNode = node.right {
stack.append(rightNode)
}
if let leftNode = node.left {
stack.append(leftNode)
}
}
return result
}
}
```