Home > Backend Development > Python Tutorial > python数据结构之二叉树的建立实例

python数据结构之二叉树的建立实例

WBOY
Release: 2016-06-16 08:44:17
Original
1768 people have browsed it

先建立二叉树节点,有一个data数据域,left,right 两个指针域

复制代码 代码如下:

# -*- coding: utf - 8 - *-

                 
class TreeNode(object):

    def __init__(self, left=0, right=0, data=0):
        self.left = left
        self.right = right
        self.data = data

复制代码 代码如下:

class BTree(object):

    def __init__(self, root=0):
        self.root = root

手动建立二叉树

复制代码 代码如下:

node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root')

bt = BTree(root)


然后会生成下面的二叉树
复制代码 代码如下:

# 生成的二叉树

# ------------------------
#          root
#       7        8
#     6
#   2   5
# 1    3 4
#
# -------------------------

除了 手动一个个的制定 node 节点,还可以创建一个 create 方法,接受用户输入添加二叉树节点。。。使用前续方式添加 ,代码如下:

复制代码 代码如下:

# -*- coding: utf - 8 - *-

           
class TreeNode(object):

    def __init__(self, left=0, right=0, data=0):
        self.left = left
        self.right = right
        self.data = data

           
class BTree(object):

    def __init__(self, root=0):
        self.root = root

    def is_empty(self):
        if self.root is 0:
            return True
        else:
            return False

    def create(self):
        temp = input('enter a value:')
        if temp is '#':
            return 0
        treenode = TreeNode(data=temp)
        if self.root is 0:
            self.root = treenode

        treenode.left = self.create()
        treenode.right = self.create()

使用create创建二叉树

复制代码 代码如下:

#运行文件 在交互解释器下面运行

bt = BTree()

bt.create()
enter a value:9
enter a value:7
enter a value:6
enter a value:2
enter a value:1
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:5
enter a value:3
enter a value:'#'
enter a value:'#'
enter a value:4
enter a value:'#'
enter a value:'#'
enter a value:'#'
enter a value:8
enter a value:'#'
enter a value:'#'

通过 create 也可以得到同样的效果

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template