File tree 2 files changed +63
-0
lines changed
2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -309,6 +309,40 @@ public class Solution {
309
309
}
310
310
```
311
311
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
+
312
346
<!-- tabs: end -->
313
347
314
348
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments