python实现二叉树的生成和递归遍历

今日主题:温故而知新。关于树的生成和遍历是好早之前就学习了的知识,最近复习数据结构,重新学习了一遍,发现就是这个简单的知识点帮助我深入理解了递归和对象,(或者是我之前基础太菜了哈哈),好吧,我们来一起复习,一起进步吧~

二叉树的生成用的是层次法,实现时,是用一个list来保存节点值,然后按照层次法把这些点一个个加入树中,然后用前序和中序遍历法来遍历,都是递归实现。递归实现千万别想复杂了,举个前序遍历的栗子:把根节点输出,然后对左子节点调用前序遍历,然后对右子节点调用。好了代码中体会吧

class Node(object):
      def __init__(self,data=-1,lchild=None,rchild=None):
            self.data=data
            self.lchild=lchild
            self.rchild=rchild


            
class BT_Tree(object):
      def __init__(self):
            self.tree=None
      def build_tree(self,nodeList):
            if len(nodeList)==0:
                  return None
            root=Node(nodeList[0])
            nodes=[root]#把nodes定义为一个node类型的集合
            i=1
            for node in nodes:
                  if node!=None:
                        if nodeList[i]!=None:
                              node.lchild=Node(nodeList[i])
                              nodes.append(node.lchild)
                              i=i+1
                              if i==len(nodeList):
                                    return root
                              if nodeList[i]!=None:
                                    node.rchild=Node(nodeList[i])
                                    nodes.append(node.rchild)
                              i=i+1
                              if i==len(nodeList):
                                    return root                      
      def digui_qianxu(self,root,x):
             if root is None:
                   return x
             else:
                   x.append(root.root)
                   self.digui_qianxu(root.lchild,x)
                   self.digui_qianxu(root.rchild,x)
                   return x
      def digui_zhongxu(self,root,x):
            if root is None:
                   return x
            else:
                  if root.lchild is not None:
                        self.digui_zhongxu(root.lchild,x)
                  x.append(root.data)
                  if root.rchild is not None:
                        self.digui_zhongxu(root.rchild,x)
                  return x
                     
             
             
if __name__ == "__main__":
      t=BT_Tree()
      nodeL=[1,2,3,4,5,6]
      t.root=t.build_tree(nodeL)
      x=[]
      y=t.digui_zhongxu(t.root,x)
      print(y)

猜你喜欢

转载自blog.csdn.net/Hedy5566/article/details/86583734