python 二叉树遍历方法大全:先序、中序、后续、递归、非递归、层次

闲来无事,又重新复习了一下二叉树遍历,最后附有完整的测试代码和运行结果。

1. 二叉树的先序遍历(非递归算法)

def preorder_traversal(root):
    # 方法1
    stack = []
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:  # 一直到最左下
            print(cur.val)
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        cur = cur.right

    # 方法2
    # if root is None:
    #     return
    # stack = [root]
    # while len(stack) != 0:
    #     cur = stack.pop()
    #     # 访问当前结点
    #     print(cur.val)
    #     if cur.right is not None:  # 先压入右子树,那么右子树在下,左子树则在上
    #         stack.append(cur.right)
    #     if cur.left is not None:
    #         stack.append(cur.left)

2. 二叉树的先序遍历(递归算法)

def preorder_traversal_recursion(root):
    if root is None:
        return
    print(root.val)
    preorder_traversal_recursion(root.left)
    preorder_traversal_recursion(root.right)

3. 二叉树的中序遍历(非递归算法)

def inorder_traversal(root):
    stack = []
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        print(cur.val)
        cur = cur.right

4. 二叉树的中序遍历(递归算法)

def inorder_traversal_recursion(root):
    if root is None:
        return
    inorder_traversal_recursion(root.left)
    print(root.val)
    inorder_traversal_recursion(root.right)

5. 二叉树的后序遍历(非递归算法)

def postorder_traversal(root):
    stack= []
    flags = []  # 0表示从左子树返回,继续访问右节点;1表示从右子树返回,弹出并访问当前结点
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:
            stack.append(cur)
            flags.append(0)
            cur = cur.left
        cur = stack.pop()
        flag = flags.pop()
        if flag == 0:
            stack.append(cur)
            flags.append(1)
            cur = cur.right
        else:
            print(cur.val)
            cur = None  # 关键一步

6. 二叉树的后序遍历(递归算法)

def postorder_traversal_recursion(root):
    if root is None:
        return
    postorder_traversal_recursion(root.left)
    postorder_traversal_recursion(root.right)
    print(root.val)

7. 二叉树的广度优先遍历(层次遍历)

def level_traversal(root):
    if root is None:
        return
    queue = [root]
    end = queue[-1]
    level = 1
    print("level " + str(level))
    while len(queue) != 0:
        cur = queue.pop(0)
        print(cur.val)
        if cur.left is not None:
            queue.append(cur.left)
        if cur.right is not None:
            queue.append(cur.right)
        if cur == end:
            level += 1
            if len(queue) != 0:
                end = queue[-1]
                print("level " + str(level))

完整测试代码和运行结果

# !usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: ywm_up
@File: binary_tree_traversal.py
@Time: 2021/8/11 10:42
"""


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class BinaryTree:
    def __init__(self):
        self.root = None

    def build_tree(self, data, index):
        if index >= len(data):
            return None
        if data[index] == "NaN":
            return None
        root = TreeNode(int(data[index]))
        left_index = 2 * index + 1
        right_index = 2 * index + 2
        root.left = self.build_tree(data, left_index)
        root.right = self.build_tree(data, right_index)
        return root

    def init_tree(self, data):
        if len(data) == 0:
            return None
        if data[0] == 'NaN':
            return None
        root = self.build_tree(data, 0)
        return root


# 1. 二叉树的先序遍历(非递归算法)
def preorder_traversal(root):
    # 方法1
    stack = []
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:  # 一直到最左下
            print(cur.val)
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        cur = cur.right

    # 方法2
    # if root is None:
    #     return
    # stack = [root]
    # while len(stack) != 0:
    #     cur = stack.pop()
    #     # 访问当前结点
    #     print(cur.val)
    #     if cur.right is not None:  # 先压右,那么右字数在栈下面,左子树在栈上面
    #         stack.append(cur.right)
    #     if cur.left is not None:
    #         stack.append(cur.left)


# 2. 二叉树的先序遍历(递归算法)
def preorder_traversal_recursion(root):
    if root is None:
        return
    print(root.val)
    preorder_traversal_recursion(root.left)
    preorder_traversal_recursion(root.right)


# 3. 二叉树的中序遍历(非递归算法)
def inorder_traversal(root):
    stack = []
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:
            stack.append(cur)
            cur = cur.left
        cur = stack.pop()
        print(cur.val)
        cur = cur.right


# 4. 二叉树的中序遍历(递归算法)
def inorder_traversal_recursion(root):
    if root is None:
        return
    inorder_traversal_recursion(root.left)
    print(root.val)
    inorder_traversal_recursion(root.right)


# 5. 二叉树的后序遍历(非递归算法)
def postorder_traversal(root):
    stack = []
    flags = []  # 0表示从左子树返回,继续访问右节点;1表示从右子树返回,弹出并访问当前结点
    cur = root
    while len(stack) != 0 or cur is not None:
        while cur is not None:
            stack.append(cur)
            flags.append(0)
            cur = cur.left
        cur = stack.pop()
        flag = flags.pop()
        if flag == 0:
            stack.append(cur)
            flags.append(1)
            cur = cur.right
        else:
            print(cur.val)
            cur = None  # 关键一步


# 6. 二叉树的后序遍历(递归算法)
def postorder_traversal_recursion(root):
    if root is None:
        return
    postorder_traversal_recursion(root.left)
    postorder_traversal_recursion(root.right)
    print(root.val)


# 7. 二叉树的广度优先遍历(层次遍历)
def level_traversal(root):
    if root is None:
        return
    queue = [root]
    end = queue[-1]
    level = 1
    print("level " + str(level))
    while len(queue) != 0:
        cur = queue.pop(0)
        print(cur.val)
        if cur.left is not None:
            queue.append(cur.left)
        if cur.right is not None:
            queue.append(cur.right)
        if cur == end:
            level += 1
            if len(queue) != 0:
                end = queue[-1]
                print("level " + str(level))


def test():
    # 用字符串数组来描述一颗二叉树
    data = ["1", "2", "3", "NaN", "5", "6", "7"]
    tree = BinaryTree()
    root = tree.init_tree(data)

    print("1. 先序非递归")
    preorder_traversal(root)
    print()

    print("2. 先序递归")
    preorder_traversal_recursion(root)
    print()

    print("3. 中序非递归")
    inorder_traversal(root)
    print()

    print("4. 中序递归")
    inorder_traversal_recursion(root)
    print()

    print("5. 后序非递归")
    postorder_traversal(root)
    print()

    print("6. 后序递归")
    postorder_traversal_recursion(root)
    print()

    print("7. 广度优先(层次遍历)")
    level_traversal(root)
    print()

    print("8. 二叉树的深度优先遍历")
    print("深度优先其实就是先序遍历")
    print()


if __name__ == '__main__':
    test()

首先我们构造的树是这样的:
在这里插入图片描述

1. 先序非递归
1
2
5
3
6
7

2. 先序递归
1
2
5
3
6
7

3. 中序非递归
2
5
1
6
3
7

4. 中序递归
2
5
1
6
3
7

5. 后序非递归
5
2
6
7
3
1

6. 后序递归
5
2
6
7
3
1

7. 广度优先(层次遍历)
level 1
1
level 2
2
3
level 3
5
6
7

8. 二叉树的深度优先遍历
深度优先其实就是先序遍历


Process finished with exit code 0
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值