Computer Science: An Overview: Global Edition (12th Edition)

Published by Pearson Higher Education
ISBN 10: 1292061162
ISBN 13: 978-1-29206-116-0

Chapter 8 - Data Abstractions - Chapter Review Problems - Page 411: 34

Answer

See the explanation

Work Step by Step

Here's a Python function to check if a binary tree is balanced: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def height(node): if node is None: return 0 return 1 + max(height(node.left), height(node.right)) 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 ``` This function defines a `TreeNode` class to represent nodes in the binary tree. The `height` function calculates the height of a given node recursively. The `is_balanced` function checks if a binary tree is balanced by comparing the heights of its left and right subtrees recursively. If the absolute difference in heights is less than or equal to 1 and both subtrees are balanced, then the tree is considered balanced.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.