Try   HackMD

Balanced Binary Tree
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

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 left and right subtrees of every node differ in height by no more than 1.

xample 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def get_height(self, node): if node == None: return 0 return 1 + max(self.get_height(node.left), self.get_height(node.right)) def isBalanced(self, root: Optional[TreeNode]) -> bool: if root == None: return True left_h = self.get_height(root.left) right_h = self.get_height(root.right) if abs(left_h - right_h) >= 2: return False return self.isBalanced(root.left) and self.isBalanced(root.right)