Skip to content

Files

Latest commit

d45ee5d · Nov 18, 2019

History

History
60 lines (43 loc) · 1.6 KB

38.md

File metadata and controls

60 lines (43 loc) · 1.6 KB

Python 树

原文: https://pythonspot.com/python-tree

介绍

在计算机科学中,树是模仿自然的数据结构。与自然界中的树不同,树数据结构是上下颠倒的:树的根在顶部。一棵树由节点组成,其连接称为边。 底部节点也称为叶节点。 一棵树可能没有循环。

tree

一棵有八个节点的树。 树的根(5)在顶部。

Python 没有对树的内置支持。

二叉树

二叉树是一种数据结构,其中每个节点最多具有两个子代(左子代和右子代)。 一棵树的根在最上面。下面的每个节点都有一个以上的节点称为父节点。我们定义一个具有leftright属性的类Tree。 从这个二叉树中,我们定义根(三个中的顶部)和一个左右节点。

#!/usr/bin/env python
class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

print(root.left.data)

然后,您可以像下面这样进一步创建树:

#!/usr/bin/env python
class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

root.left.left = Tree()
root.left.left.data = "left 2"
root.left.right = Tree()
root.left.right.data = "left-right"