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

110. Balanced Binary Tree#1013

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Ahmad-A0 merged 1 commit intoneetcode-gh:mainfromMahim1997:dev/110_swift
Sep 4, 2022
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletionsswift/110-Balanced-Binary-Tree.swift
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* 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 getMaxHeight(of root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return 1 + max(
getMaxHeight(of: root.left),
getMaxHeight(of: root.right)
)
}

func isBalanced(_ root: TreeNode?) -> Bool {
guard let root = root else { return true }

let leftHeight = getMaxHeight(of: root.left)
let rightHeight = getMaxHeight(of: root.right)
let difference = abs(leftHeight - rightHeight)

// early exits
guard difference <= 1 else { return false }
guard isBalanced(root.left) == true else { return false }
guard isBalanced(root.right) == true else { return false }

return true
}
}

[8]ページ先頭

©2009-2025 Movatter.jp