Skip to content

Commit 5ca82f9

Browse files
committed
[LeetCode Sync] Runtime - 8 ms (18.75%), Memory - 19.1 MB (7.02%)
1 parent 08ce9f0 commit 5ca82f9

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>Given a binary tree, determine if it is <span data-keyword="height-balanced"><strong>height-balanced</strong></span>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg" style="width: 342px; height: 221px;" />
6+
<pre>
7+
<strong>Input:</strong> root = [3,9,20,null,null,15,7]
8+
<strong>Output:</strong> true
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg" style="width: 452px; height: 301px;" />
13+
<pre>
14+
<strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4]
15+
<strong>Output:</strong> false
16+
</pre>
17+
18+
<p><strong class="example">Example 3:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> root = []
22+
<strong>Output:</strong> true
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>
30+
<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
31+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def isBalanced(self, root: Optional[TreeNode]) -> int:
9+
def dfs(root):
10+
if not root: return [True, 0]
11+
# [is the tree balanced? , height of tree]
12+
13+
left, right = dfs(root.left), dfs(root.right)
14+
15+
balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1
16+
return [balanced, 1 + max(left[1], right[1])]
17+
18+
return dfs(root)[0]

0 commit comments

Comments
 (0)