Swift - Stack iterative


  • 0
    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
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.