脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 教你如何使用Python实现二叉树结构及三种遍历

教你如何使用Python实现二叉树结构及三种遍历

2021-12-03 11:47小白地瓜 Python

什么是二叉树:每个节点最多有两个子树的树结构,通常子树被称作“左子树”(left subtree)和“右子树”(right subtree) 二叉树由两个对象组成,一个是节点对象,一个是树对象,需要的朋友可以参考下

一:代码实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class TreeNode:
    """节点类"""
    def __init__(self, mid, left=None, right=None):
        self.mid = mid
        self.left = left
        self.right = right
 
 
# 树类
class Tree:
    """树类"""
    def __init__(self, root=None):
        self.root = root
 
    def add(self, item):
        # 将要添加的数据封装成一个node结点
        node = TreeNode(item)
        if not self.root:
            self.root = node
            return
        queue = [self.root]
        while queue:
            cur = queue.pop(0)
            if not cur.left:
                cur.left = node
                return
            else:
                queue.append(cur.left)
 
            if not cur.right:
                cur.right = node
                return
            else:
                queue.append(cur.right)
               
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)

二:遍历

在上述树类代码基础上加遍历函数,基于递归实现。

教你如何使用Python实现二叉树结构及三种遍历

先序遍历:

先序遍历结果是:0 -> 1 -> 3 -> 4 -> 2 -> 5 -> 6

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 先序遍历
    def preorder(self, root, result=[]):
        if not root:
            return
        result.append(root.mid)
        self.preorder(root.left, result)
        self.preorder(root.right, result)
        return result
        
print("先序遍历")
print(tree.preorder(tree.root))
"""
先序遍历
[0, 1, 3, 4, 2, 5, 6]
"""

中序遍历:

中序遍历结果是:3 -> 1 -> 4 -> 0 -> 5 -> 2 -> 6

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 中序遍历
    def inorder(self, root, result=[]):
        if not root:
            return result
        self.inorder(root.left, result)
        result.append(root.mid)
        self.inorder(root.right, result)
        return result
        
print("中序遍历")
print(tree.inorder(tree.root))
"""
中序遍历
3, 1, 4, 0, 5, 2, 6]
"""

后续遍历

后序遍历结果是:3 -> 4 -> 1 -> 5 -> 6 -> 2 -> 0

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 后序遍历
    def postorder(self, root, result=[]):
        if not root:
            return result
        self.postorder(root.left, result)
        self.postorder(root.right, result)
        result.append(root.mid)
 
        return result
        
print("后序遍历")
print(tree.postorder(tree.root))
"""
后序遍历
[3, 4, 1, 5, 6, 2, 0]
"""

到此这篇关于教你如何使用Python实现二叉树结构及三种遍历的文章就介绍到这了,更多相关Python实现二叉树结构及三种遍历内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_39434183/article/details/117927680

延伸 · 阅读

精彩推荐