• 二叉树的实现


    递归的方式:
    1.二叉树遍历实现
    注意:
            1.数据构造是根据中间,左,右的方式实现的。
            2.树的建成都是由底部到顶部
            3.先序遍历【中左右】
              中序遍历【左中右】
              后序遍历【左右中】
    class TreeNode(object):
        def __init__(self, data=0,left=0,right=0):
            self.data = data
            self.left = left
            self.right = right

    class BTree(object):
        def __init__(self,root=0):
            self.root = root
        def is_empty(self):
            if self.root is 0:
                return True
            else:
                return False

        def preOrder(self,treenode):
            if treenode is 0:
                return
            print(treenode.data)
            self.preOrder(treenode.left)
            self.preOrder(treenode.right)

        def inOrder(self,treenode):
            if treenode is 0:
                return
            self.inOrder(treenode.left)
            print(treenode.data)
            self.inOrder(treenode.right)

        def postOrder(self,treenode):
            if treenode is 0:
                return
            self.postOrder(treenode.left)
            self.postOrder(treenode.right)
            print(treenode.data)

    if __name__ == '__main__':
        n1 = TreeNode(data=1)
        n2 = TreeNode(2,n1,0)
        n3 = TreeNode(3)
        n4 = TreeNode(4)
        n5 = TreeNode(5,n3,n4)
        n6 = TreeNode(6,n2,n5)
        n7 = TreeNode(7,n6,0)
        n8 = TreeNode(8)
        root = TreeNode('root',n7,n8)
        bt =BTree(root)
        print('preOrder is ')
        print(bt.preOrder(bt.root))
        print('inOrder is ')
        print(bt.inOrder(bt.root))
        print('postOrder is ')
        print(bt.postOrder(bt.root))
    运行的结果:

    preOrder is
    root 7 6 2 1 5 3 4 8 None
    inOrder is
    1 2 6 3 5 4 7 root 8 None
    postOrder is
    1 2 3 4 5 6 7 8 root None
    Process finished with exit code 0
    View Code



    优点:容易理解,使用0代替空的叶子。以null来表示结束。

    缺点:对用的数据添加有要求。不利于使用。

    改进:

    class Node(object):
        """节点类"""
        def __init__(self, item, lchild=None, rchild=None):
            self.elem = item
            self.lchild = lchild
            self.rchild = rchild
    class Tree(object):
        """树类"""
        def __init__(self):
            self.root = None
        def add(self, item):
            """为树添加节点"""
            node = Node(item)
            #如果树是空的,则对根节点赋值
            if self.root == None:#is None
                self.root = node
                return
            queue = [self.root]
            while queue:
                cur_node = queue.pop(0)#弹出队列的第一个元素
                #对已有的节点进行层次遍历
                if cur_node.lchild is None:
                    cur_node.lchild = node
                    return
                else:
                    queue.append(cur_node.lchild)
                if cur_node.rchild is None:
                    cur_node.rchild = node
                    return
                else:
                    queue.append(cur_node.rchild)
        def breadth_travel(self):
          """广度遍历:利用队列实现树的层次遍历"""
          if self.root == None:
            return
          queue = []
          queue.append(self.root)
          while queue:
            node = queue.pop(0)
            print(node.elem,end=' ')
            if node.lchild != None:
              queue.append(node.lchild)
            if node.rchild != None:
              queue.append(node.rchild)

        def preorder(self, node):
          """递归实现先序遍历"""
          if node == None:
            return
          print(node.elem,end=' ')
          self.preorder(node.lchild)
          self.preorder(node.rchild)

        def inorder(self, node):
          """递归实现中序遍历"""
          if node == None:
            return
          self.inorder(node.lchild)
          print(node.elem,end=' ')
          self.inorder(node.rchild)

        def postorder(self, node):
          """递归实现后序遍历"""
          if node == None:
            return
          self.postorder(node.lchild)
          self.postorder(node.rchild)
          print(node.elem,end=' ')
    if __name__ == '__main__':
      tree = Tree()
      #添加数
      tree.add(0)
      tree.add(1)
      tree.add(2)
      tree.add(3)
      tree.add(4)
      tree.add(5)
      tree.add(6)
      tree.add(7)
      tree.add(8)
      tree.add(9)
      print(' 广度遍历:')
      tree.breadth_travel()
      print(' 先序遍历:')
      tree.preorder(tree.root)
      print(' 中序遍历:')
      tree.inorder(tree.root)
      print(' 后序遍历:')
      tree.postorder(tree.root)

    使用非递归的实现:

    import queue
    def PreOrderWithoutRecursion(self,node):
        '''
        非递归深度优先遍历——前序遍历
        使用栈数据结构保存结点信息
        '''
        stacknode = queue.LifoQueue()
        while(node is not None or not stacknode.empty()):
            if(node is not None):
                print(node.elem, end=' ')
                stacknode.put(node.rchild)
                node = node.lchild
            else:
                node = stacknode.get()
    
    import queue
    def InOrderWithoutRecursion(self,node):
        '''
        非递归深度优先遍历——中序遍历
        使用栈数据结构保存结点信息
        '''
        stacknode = queue.LifoQueue()
        while(node is not None or not stacknode.empty()):
            if(node is not None):
                stacknode.put(node)
                node = node.lchild
            else:
                node = stacknode.get()
                print(node.elem, end=' ')
                node = node.rchild
    
    import queue
    def PostOrderWithoutRecursion(self,node):
        '''
        非递归深度优先遍历——后序遍历
        使用栈数据结构保存结点信息
        保存前一个被访问过的结点
        '''
        stacknode = queue.LifoQueue()
        pre = node
        while(node is not None):
            while (node.lchild is not None):
                stacknode.put(node)
                node = node.lchild
            while (node is not None and (node.rchild is None or node.rchild == pre)):  # 当前结点没有右孩子或者右孩子刚被访问过,则访问改结点
                print(node.elem, end=' ')
                pre = node
                if (stacknode.empty()):
                    return
                node = stacknode.get()
            stacknode.put(node)
            node = node.rchild
    View Code

    参考链接:https://www.cnblogs.com/kangna/p/11846156.html

















  • 相关阅读:
    生成纯数字随机编号的示例.sql
    程序员真的很懒
    (Coding for Concurrency).sql
    加载托管代码调试的扩展命令
    缺勤天数统计的处理示例.sql
    各种字符串合并处理示例.sql
    查询缺号分布情况的示例.sql
    控制CLR的调试
    UseCommandBehavior.cs
    Flat Icons & Icon Fonts
  • 原文地址:https://www.cnblogs.com/topass123/p/12712274.html
Copyright © 2020-2023  润新知