Last active
April 7, 2024 17:06
-
-
Save jolasjoe/fd4fb8dafdc94147dc0f97031e8ad35c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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