forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0145-binary-tree-postorder-traversal.swift
43 lines (42 loc) · 1.27 KB
/
0145-binary-tree-postorder-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
43
/**
* Question Link: https://leetcode.com/problems/binary-tree-postorder-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 postorderTraversal(_ root: TreeNode?) -> [Int] {
var res = [Int]()
var stack = [root]
var visit = [false]
while !stack.isEmpty {
let cur = stack.removeLast()
let visited = visit.removeLast()
if cur != nil {
if visited {
res.append(cur!.val)
} else {
stack.append(cur)
visit.append(true)
stack.append(cur?.right)
visit.append(false)
stack.append(cur?.left)
visit.append(false)
}
}
}
return res
}
}