python二叉树的前序遍历、中序遍历、后序遍历

本文深入讲解二叉树的前序、中序和后序遍历算法,通过实例演示了如何使用Python实现这些遍历方式,展示了每种遍历的输出结果,适合初学者理解和掌握二叉树的基本操作。

写在最前面:

接上文,上一篇我讲了如何构造一个二叉树,并且打印出来,这个打印本身是一个层次遍历,就是按一行行输出,今天我们讲一下二叉树的前序遍历、中序遍历、后序遍历

构造和打印二叉树:https://blog.youkuaiyun.com/ssjdoudou/article/details/83692895

 

'''
树的构建:
     3
  9     20
     15    7
'''

class Tree():
    '树的构造'
    def __init__(self,data, left = 0, right = 0):
        self.data = data
        self.left = left
        self.right = right


    def __str__(self):
        return str(self.data)


class MyTree():
    '二叉树的实现'
    def __init__(self,base = 0):
        self.base = base

    def _Empty(self):
        '判断是否为空树'
        if self.base == 0:
            return True
        else:
            return False

    def front_search(self,tree_base):
        '前序遍历:根-左-右'
        if tree_base == 0:
            return
        print(tree_base.data)
        self.front_search(tree_base.left)
        self.front_search(tree_base.right)

    def middle_search(self,tree_base):
        '中序遍历:左-根-右'
        if tree_base == 0:
            return
        self.middle_search(tree_base.left)
        print(tree_base.data)
        self.middle_search(tree_base.right)

    def behind_search(self,tree_base):
        '后序遍历:左-右-根'
        if tree_base == 0:
            return
        self.behind_search(tree_base.left)
        self.behind_search(tree_base.right)
        print(tree_base.data)
# test tree


tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
btree = MyTree(base)
print('前序遍历:')
btree.front_search(btree.base)
print('中序遍历:')
btree.middle_search(btree.base)
print('后序遍历:')
btree.behind_search(btree.base)

也可以这么写:

tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
print('前序遍历:')
MyTree(base).front_search(base)
print('中序遍历:')
MyTree(base).front_search(base)
print('后序遍历:')
MyTree(base).behind_search(base)

还还可以这么写:

tree1 = Tree(data=15)
tree2 = Tree(data=7)
tree3 = Tree(20,tree1,tree2)
tree4 = Tree(data=9)
base = Tree(3,tree4,tree3)
btree = MyTree()
print('前序遍历:')
btree.front_search(base)
print('中序遍历:')
btree.middle_search(base)
print('后序遍历:')
btree.behind_search(base)

这些写法都是类的灵活调用,大家自己领悟吧... 

 

输出:

前序遍历:
3
9
20
15
7
中序遍历:
9
3
15
20
7
后序遍历:
9
15
7
20
3

Process finished with exit code 0

 

### 二叉树前序、中后序遍历的递归实现 在Python中,可以使用递归方法实现二叉树前序、中后序遍历。以下是具体的实现代码: #### 前序遍历 前序遍历按照“根节点 -> 左子树 -> 右子树”的顺访问节点。 ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def preorderTraversal(root): """前序遍历""" if root is None: return [] result = [root.val] # 访问根节点 result += preorderTraversal(root.left) # 遍历左子树 result += preorderTraversal(root.right) # 遍历右子树 return result ``` #### 中序遍历序遍历按照“左子树 -> 根节点 -> 右子树”的顺访问节点。 ```python def inorderTraversal(root): """中序遍历""" if root is None: return [] result = [] result += inorderTraversal(root.left) # 遍历左子树 result.append(root.val) # 访问根节点 result += inorderTraversal(root.right) # 遍历右子树 return result ``` #### 后序遍历 后序遍历按照“左子树 -> 右子树 -> 根节点”的顺访问节点。 ```python def postorderTraversal(root): """后序遍历""" if root is None: return [] result = [] result += postorderTraversal(root.left) # 遍历左子树 result += postorderTraversal(root.right) # 遍历右子树 result.append(root.val) # 访问根节点 return result ``` 上述代码分别实现了二叉树前序、中后序遍历[^1]。通过递归调用函数,可以依次访问每个节点,并将结果存储到列表中返回。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值