可以使用数组来实现树的数据结构,每个节点包含一个value和两个子节点的索引。
下面是一个使用数组实现树的示例代码:
class Tree:
    def __init__(self, size):
        self.tree = [None] * size
        self.size = size
        
    def set_root(self, value):
        if self.tree[0] is None:
            self.tree[0] = value
        else:
            print("Root already exists")
            
    def set_left_child(self, parent_index, value):
        if self.tree[parent_index] is None:
            print("Parent node doesn't exist")
        elif parent_index * 2 + 1 >= self.size:
            print("Out of bounds")
        else:
            self.tree[parent_index * 2 + 1] = value
            
    def set_right_child(self, parent_index, value):
        if self.tree[parent_index] is None:
            print("Parent node doesn't exist")
        elif parent_index * 2 + 2 >= self.size:
            print("Out of bounds")
        else:
            self.tree[parent_index * 2 + 2] = value
            
    def get_root(self):
        return self.tree[0]
    
    def get_left_child(self, parent_index):
        if parent_index * 2 + 1 >= self.size or self.tree[parent_index * 2 + 1] is None:
            return None
        else:
            return self.tree[parent_index * 2 + 1]
        
    def get_right_child(self, parent_index):
        if parent_index * 2 + 2 >= self.size or self.tree[parent_index * 2 + 2] is None:
            return None
        else:
            return self.tree[parent_index * 2 + 2]
使用该代码,可以创建一个大小为10的树,并设置根节点和子节点的值:
tree = Tree(10)
tree.set_root("A")
tree.set_left_child(0, "B")
tree.set_right_child(0, "C")
tree.set_left_child(1, "D")
tree.set_right_child(1, "E")
通过调用get_root()和get_left_child()、get_right_child()方法,可以获取树的节点值:
print(tree.get_root())  # 输出: A
print(tree.get_left_child(0))  # 输出: B
print(tree.get_right_child(0))  # 输出: C
print(tree.get_left_child(1))  # 输出: D
print(tree.get_right_child(1))  # 输出: E