Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5603405

Browse files
authored
Merge pull requestneetcode-gh#1013 from Mahim1997/dev/110_swift
110. Balanced Binary Tree
2 parentse40ba90 +19663af commit5603405

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎swift/110-Balanced-Binary-Tree.swift

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
8+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+
* self.val = val
11+
* self.left = left
12+
* self.right = right
13+
* }
14+
* }
15+
*/
16+
classSolution{
17+
func getMaxHeight(of root:TreeNode?)->Int{
18+
guardlet root= rootelse{return0}
19+
return1+ max(
20+
getMaxHeight(of: root.left),
21+
getMaxHeight(of: root.right)
22+
)
23+
}
24+
25+
func isBalanced(_ root:TreeNode?)->Bool{
26+
guardlet root= rootelse{returntrue}
27+
28+
letleftHeight=getMaxHeight(of: root.left)
29+
letrightHeight=getMaxHeight(of: root.right)
30+
letdifference=abs(leftHeight- rightHeight)
31+
32+
// early exits
33+
guard difference<=1else{returnfalse}
34+
guardisBalanced(root.left)==trueelse{returnfalse}
35+
guardisBalanced(root.right)==trueelse{returnfalse}
36+
37+
returntrue
38+
}
39+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp