Example 6 : Check if a binary tree is height-balanced?

TopicDifficultyCompanies
Binary Tree
EASY
Amazon
Goldman Sachs

Given a binary tree, write a program to determine if the tree is height-balanced.

Problem Note

  • A height-balanced binary tree is a binary tree in which the left and right subtrees of every node differ in height by 1 or less than that.
  • If the binary tree is height balanced, return 1, else 0.

Example 1

Input: Given binary tree, [1, 2, 3, 4, 5, -1, 6, -1, -1, -1, -1, -1, -1]
1
/ \
2 3
/ \ \
4 5 6
Output: 1
Explanation: The difference between the height of left and right subtree is 1 or less than that.

Example 2

Input: Given binary tree, [1, 2, 3, -1, 4, 5, -1, 6, -1, -1, 7, -1, -1, -1, -1] 
1
/ \
2 3
\ /
4 5
/ \
6 7
Output: 0
Explanation: The difference between the height of left and right subtree is more than 1.

Code Editor

Practice and Learn

Best way to learn is through solving real problems. Practice this problem in this code editor.