Python语言基础
Python语言进阶
Python数据结构

Python 二叉树

Python 二叉树详细操作教程
树表示通过边连接的节点。它是一种非线性数据结构。它具有以下属性。
一个节点被标记为根节点。 除根节点外的每个节点都与一个父节点关联。 每个节点可以具有chib节点的编号。
我们使用前面讨论的概念os节点在python中创建树数据结构。我们将一个节点指定为根节点,然后添加更多节点作为子节点。下面是创建根节点的程序。

创建根

我们只创建一个Node类,并为该节点添加一个赋值。这变成只有根节点的树。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
    def PrintTree(self):
        print(self.data)
root = Node(10)
root.PrintTree()
运行结果如下:
10

插入树中

为了插入到树中,我们使用与上面创建的相同的节点类,并向其中添加一个插入类。插入类将节点的值与父节点进行比较,并决定将其添加为左侧节点还是右侧节点。最后,PrintTree类用于打印树。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-15
class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
    def insert(self, data):
# Compare the new value with the parent node
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data
# print the tree
    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print( self.data),
        if self.right:
            self.right.PrintTree()
# Use the insert method to add nodes
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
运行结果如下:
3 6 12 14

遍历一棵树

可以通过确定访问每个节点的顺序来遍历树。我们可以清楚地看到,我们可以从一个节点开始,然后首先访问左子树,然后再访问右子树。或者我们也可以先访问右边的子树,然后再访问左边的子树。因此,这些树遍历方法有不同的名称。我们将在此处实现树遍历算法的章节中详细研究它们。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4