-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0144-binary-tree-preorder-traversal.swift
More file actions
38 lines (37 loc) · 1.07 KB
/
0144-binary-tree-preorder-traversal.swift
File metadata and controls
38 lines (37 loc) · 1.07 KB
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
/**
* Question Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
*/
/**
* 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 preorderTraversal(_ root: TreeNode?) -> [Int] {
var stack = [TreeNode]()
var cur = root
var res = [Int]()
while cur != nil || !stack.isEmpty {
if cur != nil {
res.append(cur!.val)
if cur?.right != nil {
stack.append(cur!.right!)
}
cur = cur?.left
} else {
cur = stack.popLast()
}
}
return res
}
}