Easy Understanding Swift Solution


  • 0
    J
    func preorderTraversal(_ root: TreeNode?) -> [Int] {
      var stack: [TreeNode] = []
      var result: [Int] = []
      guard let validRoot = root else {
        return result
      }
      stack.push(validRoot)
      while let checkingNode = stack.pop() {
        result.insert(checkingNode.val, at: 0)
        if let leftNode = checkingNode.left {
          stack.push(leftNode)
        }
        if let rightNode = checkingNode.right {
          stack.push(rightNode)
        }
      }
      return result
    }
    

Log in to reply
 

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