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.