递归方法+链表实现树的构造
这个方法是比较教科书式的写法
构建二叉树节点
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())
该文章介绍了如何用递归方法和链表实现二叉树的构造。定义了一个BinaryTree类,包含初始化、插入左右子树的方法以及获取左右孩子的功能。在主函数中,创建了一个根节点并插入了左子节点和右子节点,然后打印出这些子节点。

被折叠的 条评论
为什么被折叠?



