-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbalanced-binary-tree.py
More file actions
34 lines (26 loc) · 1.16 KB
/
balanced-binary-tree.py
File metadata and controls
34 lines (26 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of
# every node never differ by more than 1.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# The expected result is to return a bool ; True -> if its balanced & False -> if not balanced
#Solution
#========
# (1) We make use of an extra function that calculates the height of a given Node ; with a simple twist -
# (2) return -1 in case, the difference between the height of left and right is > 1
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return (self.getHeight(root) >=0 )
def getHeight(self,root):
if root is None:
return 0
left_height, right_height = self.getHeight(root.left),self.getHeight(root.right)
if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1:
return -1
return max(left_height,right_height) + 1