Skip to content

Commit 2cc30eb

Browse files
committed
added balanced bst
1 parent 60572a8 commit 2cc30eb

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Diff for: 14. Questions/leetcode 110 - balanced bst.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# balanced bst | leetcode 110 | https://leetcode.com/problems/balance-a-binary-search-tree/
2+
# given a bst, check if it is balanced or not
3+
# method: for each subtree, check if its left and right subtrees and balanced, and return the maxDepth + 1
4+
5+
# Definition for a binary tree node.
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
class Solution:
13+
def isBalanced(self, root: Optional[TreeNode]) -> bool:
14+
def dfs(root):
15+
if root is None: return [True, 0]
16+
17+
left, right = dfs(root.left), dfs(root.right)
18+
balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1
19+
20+
return [balanced, max(left[1], right[1]) + 1]
21+
22+
return dfs(root)[0]

0 commit comments

Comments
 (0)