Python 关于二叉树生成、先序遍历、中序遍历、后序遍历、反转

class Node:
    def __init__(self, data, left=None, right=None):
        self.data, self.left, self.right = data, left, right


class BinTree:
    def __init__(self, root=None):
        self.root = root
        self.callback = []

    @classmethod
    def build_from(cls, node_list):
        """通过节点信息构造二叉树
        第一次遍历我们构造 node 节点
        第二次遍历我们给 root 和 孩子赋值

        :param node_list: {'data': 'A', 'left': None, 'right': None, 'is_root': False}
        """
        node_dict = {}
        root = None
        for node_data in node_list:
            node_dict[node_data['data']] = Node(node_data['data'])  # 所有节点写入节点字典中
        for node_data in node_list:
            data = node_data['data']
            node = node_dict[data]  # node_dict = {'A':Node('A')}
            if node_data['is_root']:
                root = node
            node.left = node_dict.get(node_data['left'])  # Node('A').left = Node('B') else None
            node.right = node_dict.get(node_data['right'])
        return cls(root)

    def preorder_traverse(self, subtree):
        '''
        先(根)序遍历
        :param subtree:
        :return:
        '''

        if subtree is not None:  # 该节点没有子节点就停止
            print(subtree.data)
            self.preorder_traverse(subtree.left)
            self.preorder_traverse(subtree.right)

    def midorder_traverse(self, subtree):
        '''
        中(根)序遍历
        :param subtree:
        :return:
        '''
        if subtree is not None:
            self.midorder_traverse(subtree.left)
            print(subtree.data)
            self.midorder_traverse(subtree.right)

    def lastorder_traverse(self, subtree):
        '''
        后(根)序遍历
        :param subtree:
        :return:
        '''
        if subtree is not None:
            self.lastorder_traverse(subtree.left)
            self.lastorder_traverse(subtree.right)
            self.callback.append(subtree.data)

    def reverse(self, subtree):
        if subtree is not None:
            subtree.left, subtree.right = subtree.right, subtree.left
            self.reverse(subtree.left)
            self.reverse(subtree.right)


node_list = [
    {'data': 'A', 'left': 'B', 'right': 'C', 'is_root': True},
    {'data': 'B', 'left': 'D', 'right': 'E', 'is_root': False},
    {'data': 'D', 'left': None, 'right': None, 'is_root': False},
    {'data': 'E', 'left': 'H', 'right': None, 'is_root': False},
    {'data': 'H', 'left': None, 'right': None, 'is_root': False},
    {'data': 'C', 'left': 'F', 'right': 'G', 'is_root': False},
    {'data': 'F', 'left': None, 'right': None, 'is_root': False},
    {'data': 'G', 'left': 'I', 'right': 'J', 'is_root': False},
    {'data': 'I', 'left': None, 'right': None, 'is_root': False},
    {'data': 'J', 'left': None, 'right': None, 'is_root': False},
]


def tree(node_list):
    nodes = {}
    datas = []
    root = None
    for nodedata in node_list:
        data = nodedata['data']
        left = nodedata['left']
        right = nodedata['right']
        nodes[data] = Node(data, left, right)
        datas.append(data)
        # 所有节点均有了,nodes= {'A':Node('A'),'B':Node('B')}
        # Node('A'):{'data':'A',left:'B',right:'C'}
    for nodedata in node_list:
        data = nodedata['data']  # 'A','B','C'
        node = nodes[data]
        if nodedata['is_root']:
            root = node
        try:
            node.left = nodes[node.left]
        except KeyError:
            node.left = None
        node.right = nodes.get(nodedata['right'])

    return root


if __name__ == '__main__':
    btree = BinTree.build_from(node_list)
    # btree.preorder_traverse(btree.root)  # 输出 A, B, D, E, H, C, F, G, I, J
    # btree.midorder_traverse(btree.root)
    btree.lastorder_traverse(btree.root)
    print(btree.callback)
    btree.reverse(btree.root)
    print(btree.root)

 

posted @ 2018-08-23 18:40  来呀快活吧  阅读(669)  评论(0编辑  收藏  举报
cs