Skip to content

Commit 24c31c4

Browse files
authored
feat: add swift implementation to lcof problem: No.55.2 (doocs#2942)
1 parent c3034e3 commit 24c31c4

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

lcof/面试题55 - II. 平衡二叉树/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,40 @@ public class Solution {
309309
}
310310
```
311311

312+
#### Swift
313+
314+
```swift
315+
/* public class TreeNode {
316+
* public var val: Int
317+
* public var left: TreeNode?
318+
* public var right: TreeNode?
319+
* public init(_ val: Int) {
320+
* self.val = val
321+
* self.left = nil
322+
* self.right = nil
323+
* }
324+
* }
325+
*/
326+
327+
class Solution {
328+
func isBalanced(_ root: TreeNode?) -> Bool {
329+
return dfs(root) != -1
330+
}
331+
332+
private func dfs(_ root: TreeNode?) -> Int {
333+
guard let root = root else {
334+
return 0
335+
}
336+
let leftDepth = dfs(root.left)
337+
let rightDepth = dfs(root.right)
338+
if leftDepth == -1 || rightDepth == -1 || abs(leftDepth - rightDepth) > 1 {
339+
return -1
340+
}
341+
return 1 + max(leftDepth, rightDepth)
342+
}
343+
}
344+
```
345+
312346
<!-- tabs:end -->
313347

314348
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* public class TreeNode {
2+
* public var val: Int
3+
* public var left: TreeNode?
4+
* public var right: TreeNode?
5+
* public init(_ val: Int) {
6+
* self.val = val
7+
* self.left = nil
8+
* self.right = nil
9+
* }
10+
* }
11+
*/
12+
13+
class Solution {
14+
func isBalanced(_ root: TreeNode?) -> Bool {
15+
return dfs(root) != -1
16+
}
17+
18+
private func dfs(_ root: TreeNode?) -> Int {
19+
guard let root = root else {
20+
return 0
21+
}
22+
let leftDepth = dfs(root.left)
23+
let rightDepth = dfs(root.right)
24+
if leftDepth == -1 || rightDepth == -1 || abs(leftDepth - rightDepth) > 1 {
25+
return -1
26+
}
27+
return 1 + max(leftDepth, rightDepth)
28+
}
29+
}

0 commit comments

Comments
 (0)