如何在Python中实现树?在Python中是否有任何内置的数据结构? [英] How can I implement a tree in Python? Are there any built in data structures in Python like in Java?
本文介绍了如何在Python中实现树?在Python中是否有任何内置的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
Python没有相当广泛的Java内置的内置数据结构。但是,由于Python是动态的,所以一般的树很容易创建。例如,二叉树可能是:
类树(对象):
def __init __(self):
self.left =无
self.right =无
self.data =无
您可以这样使用:
root = Tree()
root.data = root
root.left = Tree()
root.left.data =left
root.right = Tree()
root.right.data =right
I am trying to construct a general tree. Are there any built in data structures in Python to implement a tree?
解决方案
Python doesn't have the quite the extensive range of "built-in" data structures as Java does. However, because Python is dynamic, a general tree is easy to create. For example, a binary tree might be:
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None
You can use it like this:
root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"
这篇关于如何在Python中实现树?在Python中是否有任何内置的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文