ตรวจสอบ Binary Tree ว่าสมดุลแบบ Red-Black Tree
ใน Red-Black Tree ความสูงสูงสุดของโหนดจะไม่เกินสองเท่าของความสูงต่ำสุด สำหรับ Binary Search Tree ทั่วไป เราต้องตรวจสอบคุณสมบัติดังนี้: สำหรับทุกโหนด ความยาวของเส้นทางจากโหนดไปยังใบที่ไกลที่สุด (longest leaf-to-node path) ต้องไม่เกินสองเท่าของจำนวนโหนดบนเส้นทางสั้นที่สุดจากโหนดไปยังใบ (shortest node-to-leaf path)
ตัวอย่าง
หากโครงสร้างต้นไม้เป็นดังรูป (ไม่สามารถแสดงรูปได้ในข้อความ) ผลลัพธ์จะเป็น True เนื่องจากต้นไม้นี้สมดุล
ขั้นตอนการแก้ปัญหา
- กำหนดฟังก์ชัน
solve(root, max_height, min_height)ที่รับรากของต้นไม้ปัจจุบันและตัวแปรอ้างอิงสำหรับความสูงสูงสุดและต่ำสุด - ถ้า
rootเป็นNone:- ตั้ง
max_height = 0,min_height = 0 - คืนค่า
True
- ตั้ง
- กำหนดตัวแปรสำหรับต้นไม้ย่อยซ้ายและขวา:
left_max, left_min, right_max, right_min - เรียก
solveแบบเวียนเกิดสำหรับลูกซ้ายและขวา หากใดด้านหนึ่งคืนFalseให้คืนFalseทันที - คำนวณค่าความสูง:
max_height = max(left_max, right_max) + 1min_height = min(left_min, right_min) + 1
- ตรวจสอบเงื่อนไขสมดุล:
max_height <= 2 * min_heightหากเป็นจริงคืนTrueมิฉะนั้นFalse - ในฟังก์ชันหลัก ให้เรียก
solve(root, 0, 0)
โค้ดตัวอย่าง Python
class TreeNode:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def solve(root, max_height, min_height):
if root is None:
max_height = min_height = 0
return True
left_max = left_min = 0
right_max = right_min = 0
if not solve(root.left, left_max, left_min):
return False
if not solve(root.right, right_max, right_min):
return False
max_height = max(left_max, right_max) + 1
min_height = min(left_min, right_min) + 1
return max_height <= 2 * min_height
def is_tree_balanced(root):
return solve(root, 0, 0)
# ตัวอย่างการใช้งาน
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(100)
root.right.left = TreeNode(50)
root.right.right = TreeNode(150)
root.right.left.left = TreeNode(40)
print(is_tree_balanced(root)) # True
อินพุต / เอาต์พุต
Input: root = TreeNode(10) ... (ตามโค้ด)
Output: True