Skip to content

Instantly share code, notes, and snippets.

@jolasjoe
Last active April 7, 2024 17:06
Show Gist options
  • Save jolasjoe/fd4fb8dafdc94147dc0f97031e8ad35c to your computer and use it in GitHub Desktop.
Save jolasjoe/fd4fb8dafdc94147dc0f97031e8ad35c to your computer and use it in GitHub Desktop.
public class TreeNode {
public let val: Int
public var left: TreeNode?
public var right: TreeNode?
init(_ val: Int) {
self.val = val
}
}
func inorder(_ root: TreeNode) -> [Int] {
var stack = [TreeNode]()
var result = [Int]()
var current: TreeNode? = root
while current != nil || !stack.isEmpty {
if let currentNode = current {
stack.append(currentNode)
current = currentNode.left
} else {
let popped = stack.removeLast()
result.append(popped.val)
current = popped.right
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment