美文网首页
python 实现树

python 实现树

作者: 云之彼端09 | 来源:发表于2018-10-18 09:23 被阅读5次

    创建树,遍历树,反转树

    thinking:用到的思想都是递归
    递归一定要有结束条件
    
    class Bnode(object):
        def __init__(self, data, left=None, right=None):
            self.data = data
            self.left = left
            self.right = right
    
    
    class Btree(object):
        def __init__(self, root=None):
            self.root = root
    
        '''
        build_from
        :param node_list: {'data': 'A', 'left': None, 'right': None, 'is_root': False}
        '''
        @classmethod
        def bulid(cls, list):
            node_dict = {}
            # 制作节点
            for item in list:
                data = item['data']
                node_dict[data] = Bnode(data)
            # 把节点组装成数
            for item in list:
                data = item['data']
                node = node_dict[data]
                if node['is_root']:
                    root = node
                node.left = node_dict.get(item['left'])
                node.right = node_dict.get(item['right'])
            return cls(root)
    
        def preorder(self, subtree):
            # 先序
            if subtree is not None:
                print(subtree.data)
                self.preorder(subtree.left)
                self.preorder(subtree.right)
    
        '''反转'''
    
        def reverse(self, subtree):
            if subtree is not None:
                subtree.left, subtree.right = subtree.right, subtree.left
                self.reverse(self, subtree.left)
                self.reverse(self, subtree.right)
    
    

    相关文章

      网友评论

          本文标题:python 实现树

          本文链接:https://www.haomeiwen.com/subject/uqzlzftx.html