เมื่อต้องการหาผลรวมค่าของโหนดทั้งหมดใน Binary Tree ใช้ Recursion ผ่านทุกโหนด รวมค่า key ของโหนดปัจจุบันกับผลรวมจากลูกซ้ายและลูกขวา
ตัวอย่างโค้ด
class TreeNode:
def __init__(self, data):
self.key = data
self.left = None
self.right = None
def sum_nodes(self):
total = self.key
if self.left:
total += self.left.sum_nodes()
if self.right:
total += self.right.sum_nodes()
return total
# Build tree manually for demo
root = TreeNode(5)
root.left = TreeNode(7)
root.right = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
print("Sum of all nodes:", root.sum_nodes())ผลลัพธ์
Sum of all nodes: 21
คำอธิบาย
คลาส
TreeNodeแทนโหนดมี key, left, rightเมธอด
sum_nodes()เรียกซ้ำ (recursive)Base case: ถ้าโหนดเป็น None คืน 0 (จัดการใน if)
Recursive case: key + sum(left) + sum(right)
Tree ตัวอย่าง: 5 + 7 + 3 + 2 + 4 = 21