Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python tính tổng tất cả nút trong cây nhị phân

Triển khai cây tổng quát (không nhị phân) với danh sách con, dùng đệ quy tính tổng giá trị các nút.

Ví dụ

class TreeNode:
    def __init__(self, data):
        self.key = data
        self.children = []

    def add_child(self, node):
        self.children.append(node)

    def find_node(self, key):
        if self.key == key:
            return self
        for child in self.children:
            res = child.find_node(key)
            if res:
                return res
        return None

    def sum_nodes(self):
        total = self.key
        for child in self.children:
            total += child.sum_nodes()
        return total

# Demo tương tác
root = None
while True:
    cmd = input("Cmd (add/sum/quit): ").split()
    if not cmd: continue
    if cmd[0] == 'add':
        val = int(cmd[1])
        node = TreeNode(val)
        if cmd[2] == 'at':
            root = node
        else:  # below
            parent = root.find_node(int(cmd[3]))
            if parent:
                parent.add_child(node)
    elif cmd[0] == 'sum':
        if root:
            print("Tổng:", root.sum_nodes())
        else:
            print("Cây rỗng")
    elif cmd[0] == 'quit':
        break

Kết quả

Cmd (add/sum/quit): add 5 at root
Cmd (add/sum/quit): add 7 below 5
Cmd (add/sum/quit): add 0 below 7
Cmd (add/sum/quit): sum
Tổng: 12
Cmd (add/sum/quit): quit

Giải thích

  • Class TreeNode lưu giá trị và list con.
  • sum_nodes đệ quy: tổng = key + tổng các con.
  • Menu cho phép xây cây động: add at root, add below key, sum, quit.
  • Tìm nút cha bằng find_node đệ quy.