Skip to content

Commit 44b9bbd

Browse files
authored
feat: add swift implementation to lcof problem: No.33 (doocs#2903)
1 parent 24ec9b7 commit 44b9bbd

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lcof/面试题33. 二叉搜索树的后序遍历序列/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,36 @@ public class Solution {
269269
}
270270
```
271271

272+
#### Swift
273+
274+
```swift
275+
class Solution {
276+
private var postorder: [Int] = []
277+
278+
func verifyPostorder(_ postorder: [Int]) -> Bool {
279+
self.postorder = postorder
280+
return dfs(0, postorder.count - 1)
281+
}
282+
283+
private func dfs(_ l: Int, _ r: Int) -> Bool {
284+
if l >= r {
285+
return true
286+
}
287+
let rootValue = postorder[r]
288+
var i = l
289+
while i < r && postorder[i] < rootValue {
290+
i += 1
291+
}
292+
for j in i..<r {
293+
if postorder[j] < rootValue {
294+
return false
295+
}
296+
}
297+
return dfs(l, i - 1) && dfs(i, r - 1)
298+
}
299+
}
300+
```
301+
272302
<!-- tabs:end -->
273303

274304
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
private var postorder: [Int] = []
3+
4+
func verifyPostorder(_ postorder: [Int]) -> Bool {
5+
self.postorder = postorder
6+
return dfs(0, postorder.count - 1)
7+
}
8+
9+
private func dfs(_ l: Int, _ r: Int) -> Bool {
10+
if l >= r {
11+
return true
12+
}
13+
let rootValue = postorder[r]
14+
var i = l
15+
while i < r && postorder[i] < rootValue {
16+
i += 1
17+
}
18+
for j in i..<r {
19+
if postorder[j] < rootValue {
20+
return false
21+
}
22+
}
23+
return dfs(l, i - 1) && dfs(i, r - 1)
24+
}
25+
}

0 commit comments

Comments
 (0)