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

  

转载于:https://www.cnblogs.com/aguncn/p/10693337.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值