Tree01-BuildingTree-NodeLinkedTable-RecursiveMethod

该文章介绍了如何用递归方法和链表实现二叉树的构造。定义了一个BinaryTree类,包含初始化、插入左右子树的方法以及获取左右孩子的功能。在主函数中,创建了一个根节点并插入了左子节点和右子节点,然后打印出这些子节点。
摘要由CSDN通过智能技术生成

递归方法+链表实现树的构造
这个方法是比较教科书式的写法

构建二叉树节点


class BinaryTree:
    def __init__(self, root):
        self.key = root
        self.leftchild = None
        self.rightchild = None

插入左子树

	def insertleft(self, newnode):
	        if self.leftchild is None:
	            self.leftchild = BinaryTree(newnode)
	        else:
	            t = BinaryTree(newnode)
	            t.leftchild = self.leftchild
	            self.leftchild = t          

插入右子树

	def insertright(self, newnode):
	        if self.rightchild is None:
	            self.rightchild = BinaryTree(newnode)
	        else:
	            t = BinaryTree(newnode)
	            t.rightchild = self.rightchild
	            self.rightchild = t

返回左孩子

	def getleftchild(self):
	        if self.key is None:
	            return
	        else:
	            if self.leftchild is None:
	                return
	            else:
	                return self.leftchild.key

返回右孩子

	def getrightchild(self):
	        if self.key is None:
	            return
	        else:
	            if self.rightchild is None:
	                return
	            else:
	                return self.rightchild.key

主函数

if __name__ == "__main__":
    
    tree = BinaryTree(0)
    tree.insertleft(1)
    tree.insertright(2)
    print(tree.getleftchild())
    print(tree.getrightchild())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值