Python二叉树

Python二叉树 首页 / 数据结构入门教程 / Python二叉树

树(Tree)表示通过边连接的节点,它是一种非线性数据结构,它具有以下属性。

  • 一个节点被标签为"root "根节点。
  • 除根节点外,每个节点都与一个父节点关联。
  • 每个节点可以具有子节点(child)的编号。

无涯教程将一个节点指定为根节点,然后添加更多节点作为子节点,下面是创建根节点的程序。

创建根节点

只创建一个Node类,并向该节点添加一个赋值。这变成只有根节点的树。

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()

执行以上代码后,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-binary-tree.html

来源:LearnFk无涯教程网

10

插入节点到树

为了插入到树中,使用与上面创建的相同的节点类,并向其中添加一个插入节点,插入类比较值将该节点添加到父节点,并决定将其添加为左节点还是右节点。最后,PrintTree类用于打印树。

class Node:

    def __init__(self, data):

        self.left=None
        self.right=None
        self.data=data

    def insert(self, data):
# 将新值与父节点进行比较
        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

# 打印树
    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print( self.data),
        if self.right:
            self.right.PrintTree()

# 使用insert方法添加节点
root=Node(12)
root.insert(6)
root.insert(14)
root.insert(3)

root.PrintTree()

执行以上代码后,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/python-data-structure/python-binary-tree.html

来源:LearnFk无涯教程网

3 6 12 14

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

后端工程师的高阶面经 -〔邓明〕

快速上手C++数据结构与算法 -〔王健伟〕

手把手教你落地DDD -〔钟敬〕

Web 3.0入局攻略 -〔郭大治〕

React Native 新架构实战课 -〔蒋宏伟〕

深入C语言和程序运行原理 -〔于航〕

大厂晋升指南 -〔李运华〕

软件设计之美 -〔郑晔〕

持续交付36讲 -〔王潇俊〕

好记忆不如烂笔头。留下您的足迹吧 :)