-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0094.Binary Tree Inorder Traversal.swift
42 lines (38 loc) · 1.22 KB
/
0094.Binary Tree Inorder Traversal.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
guard let root = root else {
return []
}
// recursive
// return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
var result = [Int]()
var stack = [TreeNode?]()
var current: TreeNode? = root
while(!stack.isEmpty || current != nil) {
if let curr = current {
stack.append(curr)
current = curr.left
} else {
current = stack.removeLast()!
result.append(current!.val)
current = current!.right
}
}
return result
}
}