Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 3 additions & 1 deletion problems/balanced-binary-tree/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
<p>For this problem, a height-balanced binary tree is defined as:</p>

<blockquote>
<p>a binary tree in which the depth of the two subtrees of <em>every</em> node never differ by more than 1.</p>
<p>a binary tree in which the left and right subtrees of <em>every</em> node differ in height by no more than 1.</p>
</blockquote>

<p>&nbsp;</p>

<p><strong>Example 1:</strong></p>

<p>Given the following tree <code>[3,9,20,null,null,15,7]</code>:</p>
Expand Down
39 changes: 38 additions & 1 deletion problems/balanced-binary-tree/balanced_binary_tree.go
Original file line number Diff line number Diff line change
@@ -1 +1,38 @@
package balanced_binary_tree
package problem_110

import "github.com/openset/leetcode/internal/kit"

type TreeNode = kit.TreeNode

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
_, isBalanced := recur(root)
return isBalanced
}

func recur(root *TreeNode) (int, bool) {
if root == nil {
return 0, true
}
leftDepth, leftIsBalanced := recur(root.Left)
rightDepth, rightIsBalanced := recur(root.Right)
if leftIsBalanced && rightIsBalanced &&
-1 <= leftDepth-rightDepth && leftDepth-rightDepth <= 1 {
return max(leftDepth, rightDepth) + 1, true
}
return 0, false
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
2 changes: 1 addition & 1 deletion problems/balanced-binary-tree/balanced_binary_tree_test.go
Original file line number Diff line number Diff line change
@@ -1 +1 @@
package balanced_binary_tree
package problem_110