Is Height Balanced Binary Tree Problem Statement

Determine if the given binary tree is height-balanced. A tree is considered height-balanced when:

  1. The left subtree is balanced.
  2. The right subtree is balanced.
  3. The height difference between the left and the right subtree is at most 1.

The height of a tree is defined as the maximum number of nodes in the path from the node to any leaf node. An empty tree is balanced by definition.

Input:

The first line contains an integer 'T' denoting the number of test cases. Each test case is a sequence of node values in level order, separated by spaces. Use -1 to signify a non-existent child.

Output:

For each test case, return ‘True’ if the tree is height-balanced, otherwise return ‘False’.

Example:

Consider this binary tree:

schema of a binary tree
The input for this tree in level order might look like:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Explanation:

  • Level 1: The root node value is 1
  • Level 2: Left child of 1 is 2, Right child is 3
  • Level 3: Left child of 2 is 4, Right child is none, Left child of 3 is 5, Right child is 6
  • Level 4 and beyond: Details the connections to and existence of further child nodes, following similar rules.

For this tree, evaluate each subtree as per the height-balanced conditions outlined.

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 3000
  • -109 ≤ data ≤ 109, data ≠ -1
Note:

The input format eliminates null nodes by replacing them with -1. For ease, input ends when the description of all nodes at a given level are null (-1). Implement the function, no need to handle I/O procedures.

Be the first one to answer
Add answer anonymously...
Josh Technology Group Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter