Skip to content

Commit 359c46c

Browse files
author
openset
committed
Add: Balanced Binary Tree
1 parent 6832936 commit 359c46c

File tree

3 files changed

+42
-3
lines changed

3 files changed

+42
-3
lines changed

Diff for: problems/balanced-binary-tree/README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@
1616
<p>For this problem, a height-balanced binary tree is defined as:</p>
1717

1818
<blockquote>
19-
<p>a binary tree in which the depth of the two subtrees of <em>every</em> node never differ by more than 1.</p>
19+
<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>
2020
</blockquote>
2121

22+
<p>&nbsp;</p>
23+
2224
<p><strong>Example 1:</strong></p>
2325

2426
<p>Given the following tree <code>[3,9,20,null,null,15,7]</code>:</p>
+38-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,38 @@
1-
package balanced_binary_tree
1+
package problem_110
2+
3+
import "github.com/openset/leetcode/internal/kit"
4+
5+
type TreeNode = kit.TreeNode
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* type TreeNode struct {
10+
* Val int
11+
* Left *TreeNode
12+
* Right *TreeNode
13+
* }
14+
*/
15+
func isBalanced(root *TreeNode) bool {
16+
_, isBalanced := recur(root)
17+
return isBalanced
18+
}
19+
20+
func recur(root *TreeNode) (int, bool) {
21+
if root == nil {
22+
return 0, true
23+
}
24+
leftDepth, leftIsBalanced := recur(root.Left)
25+
rightDepth, rightIsBalanced := recur(root.Right)
26+
if leftIsBalanced && rightIsBalanced &&
27+
-1 <= leftDepth-rightDepth && leftDepth-rightDepth <= 1 {
28+
return max(leftDepth, rightDepth) + 1, true
29+
}
30+
return 0, false
31+
}
32+
33+
func max(a, b int) int {
34+
if a > b {
35+
return a
36+
}
37+
return b
38+
}
+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
package balanced_binary_tree
1+
package problem_110

0 commit comments

Comments
 (0)