python--使用递归的方式建立二叉树

时间:2024-12-25 17:33:50

树和图的数据结构,就很有意思啦。

python--使用递归的方式建立二叉树

# coding = utf-8

class BinaryTree:
    def __init__(self, root_obj):
        self.key = root_obj
        self.left_child = None
        self.right_child = None

    def insert_left(self, new_node):
        node = BinaryTree(new_node)
        if self.left_child is None:
            self.left_child = node
        else:
            node.left_child = self.left_child
            self.left_child = node

    def insert_right(self, new_node):
        node = BinaryTree(new_node)
        if self.right_child is None:
            self.right_child = node
        else:
            node.right_child = self.right_child
            self.right_child = node

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def set_root_val(self, obj):
        self.key = obj

    def get_root_val(self):
        return self.key

root = BinaryTree('a')
print(root.get_root_val())
print(root.get_left_child())
root.insert_left('b')
print(root.get_left_child())
print(root.get_left_child().get_root_val())
root.insert_right('c')
print(root.get_right_child())
print(root.get_right_child().get_root_val())
root.get_right_child().set_root_val('hello')
print(root.get_right_child().get_root_val())

  

C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
a
None
<__main__.BinaryTree object at 0x00000000024139B0>
b
<__main__.BinaryTree object at 0x00000000024139E8>
c
hello

Process finished with exit code 0

  

相关文章