Skip to content

Instantly share code, notes, and snippets.

@gabrielepalma
Created December 9, 2022 17:36
Show Gist options
  • Save gabrielepalma/0771ae048cf7f0c6f2f5d90c1a73aa74 to your computer and use it in GitHub Desktop.
Save gabrielepalma/0771ae048cf7f0c6f2f5d90c1a73aa74 to your computer and use it in GitHub Desktop.
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var stack: [(TreeNode, Bool)] = (root != nil) ? [(root!, true)] : []
var output:[Int] = []
while let (node, unvisited) = stack.popLast() {
guard unvisited else {
output.append(node.val)
print(node.val)
continue
}
if let right = node.right {
stack.append((right, true))
}
stack.append((node, false))
if let left = node.left {
stack.append((left, true))
}
}
return output
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment