-
Notifications
You must be signed in to change notification settings - Fork 889
/
InorderTraversal.swift
35 lines (33 loc) · 1011 Bytes
/
InorderTraversal.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
/**
* Question Link: https://leetcode.com/problems/binary-tree-inorder-traversal/
* Primary idea: Use a stack to help iterate the tree
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class InorderTraversal {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int](), stack = [TreeNode](), node = root
while node != nil || !stack.isEmpty {
if let currentNode = node {
stack.append(currentNode)
node = currentNode.left
} else {
let prevNode = stack.removeLast()
res.append(prevNode.val)
node = prevNode.right
}
}
return res
}
}