python:二叉树的前、中、后序遍历的两种写法

import collections


class BiTree(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def nums_to_tree(nums):
    if not nums:
        return []

    queue = collections.deque()
    root = BiTree(nums[0])
    queue.append(root)
    i = 1
    while i < len(nums):
        node = queue.popleft()
        if i < len(nums) and nums[i] != -1:
            node.left = BiTree(nums[i])
            queue.append(node.left)
        i += 1
        if i < len(nums) and nums[i] != -1:
            node.right = BiTree(nums[i])
            queue.append(node.right)
        i += 1
    return root


# 前序遍历的第一种写法
def pre_sort_1(root):
    res = []

    def backtracking(root):
        if not root:
            return None

        res.append(root.val)
        backtracking(root.left)
        backtracking(root.right)

    backtracking(root)
    return res


# 前序遍历的第二种写法
def pre_sort_2(root):
    if not root:
        return []

    left = pre_sort_2(root.left)
    right = pre_sort_2(root.right)

    return [root.val] + left + right

# 中序遍历的第一种写法
def in_sort_1(root):
    res = []

    def backtracking(root):
        if not root:
            return None

        backtracking(root.left)
        res.append(root.val)
        backtracking(root.right)

    backtracking(root)
    return res


# 中序遍历的第二种写法
def in_sort_2(root):
    if not root:
        return []

    left = in_sort_2(root.left)
    right = in_sort_2(root.right)

    return left + [root.val] + right


# 后序遍历的第一种写法
def post_sort_1(root):
    res = []

    def backtracking(root):
        if not root:
            return None

        backtracking(root.left)
        backtracking(root.right)
        res.append(root.val)

    backtracking(root)
    return res


# 后序遍历的第二种写法
def post_sort_2(root):
    if not root:
        return []

    left = post_sort_2(root.left)
    right = post_sort_2(root.right)

    return left + right + [root.val]


# 输入为 1 2 3 null 4 null 5
#      1
#    /   \
#   2     3
#    \     \
#     4     5


if __name__ == '__main__':
    nums = [1, 2, 3, 'null', 4, 'null', 5]
    nums = [int(i) if i != 'null' else -1 for i in nums]
    root = nums_to_tree(nums)
    print(pre_sort_1(root))
    print(pre_sort_2(root))
    print(in_sort_1(root))
    print(in_sort_2(root))
    print(post_sort_1(root))
    print(post_sort_2(root))

结果

[1, 2, 4, 3, 5]
[1, 2, 4, 3, 5]
[2, 4, 1, 3, 5]
[2, 4, 1, 3, 5]
[4, 2, 5, 3, 1]
[4, 2, 5, 3, 1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值