数据结构(二)二叉树的遍历

# -*- coding: UTF-8 -*-


class Node(object):
    def __init__(self, val):
        self.__val = val
        self.__left = None  # 声明一个成员属性
        self.__right = None

    def set_val(self, val):
        self.__val = val

    def set_left(self, left):
        self.__left = left

    def set_right(self, right):
        self.__right = right

    def get_val(self):
        return self.__val

    def get_left(self):
        return self.__left

    def get_right(self):
        return self.__right


# 前序遍历
def pre_order_traverse(root):
    if root is None:
        return

    print(root.get_val())
    pre_order_traverse(root.get_left())
    pre_order_traverse(root.get_right())


# 中序遍历
def in_order_traverse(root):
    if root is None:
        return

    in_order_traverse(root.get_left())
    print(root.get_val())
    in_order_traverse(root.get_right())


# 后序遍历
def post_order_traverse(root):
    if root is None:
        return

    post_order_traverse(root.get_left())
    post_order_traverse(root.get_right())
    print(root.get_val())


# 定义一棵二叉树
#       1
#       /\
#      2  3
#      /\  \
#     4  5  6

node1 = Node(1)
node2 = Node(2)
node1.set_left(node2)
node3 = Node(3)
node1.set_right(node3)
node4 = Node(4)
node2.set_left(node4)
node5 = Node(5)
node2.set_right(node5)
node6 = Node(6)
node3.set_right(node6)

# 前序遍历
print("前序遍历")
pre_order_traverse(node1)

# 中序遍历
print("中序遍历")
in_order_traverse(node1)

# 后序遍历
print("后序遍历")
post_order_traverse(node1)

你可能感兴趣的:(数据结构(二)二叉树的遍历)