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]

你可能感兴趣的:(算法,python,开发语言,算法)