Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
106 views
in Information Technology by (178k points)
Find if Binary Tree Satisfies Balanced Height Property

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

To determine if a binary tree satisfies the balanced height property, we need to define what "balanced height" means for a binary tree. In this context, a binary tree is considered balanced if the height of its left and right subtrees differ by at most one for every node in the tree.

Here's a Python function to check if a binary tree satisfies the balanced height property:

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def height(node):
    if node is None:
        return 0
    return max(height(node.left), height(node.right)) + 1

def is_balanced(root):
    if root is None:
        return True

    left_height = height(root.left)
    right_height = height(root.right)

    if abs(left_height - right_height) <= 1 and \
       is_balanced(root.left) and is_balanced(root.right):
        return True
    return False

# Example usage:
# Construct a binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)

# Check if the binary tree is balanced
print(is_balanced(root))  # Output: False
 

This code defines a TreeNode class to represent each node in the binary tree. The height() function calculates the height of a subtree rooted at a given node. The is_balanced() function recursively checks if the binary tree satisfies the balanced height property by comparing the heights of its left and right subtrees. If the height difference is at most one for every node and both left and right subtrees are balanced, the tree is considered balanced.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...