zoukankan      html  css  js  c++  java
  • 层序遍历二叉树 完整层序重建二叉树 python

      给定一个二叉树的完整的层次遍历序列(包含所有节点,包括空节点),利用这个序列生成一颗二叉树。

      我们首先来看怎样对一颗二叉树进行层序遍历,下图所示的二叉树层次遍历的结果为[a,b,c,d,e],在这个过程中,我们首先保存根节点a,然后遍历a的左右节点b,d并保存下来,然后遍历b的左右子节点并保存,然后遍历d的子节点并保存,直到完成了整棵树的遍历。所以这个过程是一个保存节点然后取出遍历的过程,它符合先进先出的顺序,所以才用队列来实现

    首先定义二叉树的类:

    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None

      层序遍历:

     1 def PrintFromTopToBottom(root):
     2         ans=[]
     3         if root==None:
     4             return ans
     5         else:
     6             q=[root]
     7             while q:
     8                 node=q.pop(0)
     9                 ans.append(node.val)
    10                 if node.left:
    11                     q.append(node.left)
    12                 if node.right:
    13                     q.append(node.right)
    14             return ans

      利用层序生成二叉树则是一个相反的过程,对于序列[a,b,c,d,None,None,e]来说,b  c是a的子节点,d  None是b的子节点,None  e是c的子节点。如果序列为l,那么l[0]是根节点,l[1]和l[2]是l[0]左右子结点,l[3]和l[4]是l[1]左右子节点......,所以每次取出两个节点,依次作为之前节点的子节点。代码如下:

     1 def createtree(l):
     2         if l[0]:
     3             root=TreeNode(l[0])
     4             nodes=[root]
     5             id=1
     6             while nodes and id<len(l):
     7                 node=nodes[0]#依次为每个节点分配子节点
     8                 node.left=TreeNode(l[id]) if l[id] else None
     9                 nodes.append(node.left)
    10                 node.right=TreeNode(l[id+1]) if id<len(l)-1 and l[id+1] else None
    11                 nodes.append(node.right)
    12                 id+=2#每次取出两个节点
    13                 nodes.pop(0)
    14             return root
    15         else:
    16             return None

    python版本:3.6

  • 相关阅读:
    个人工作总结6
    使用java对文件批量重命名
    导入csv文件到数据库
    关于微信小程序的Request请求错误处理
    基于jPlayer的三分屏制作
    条件查询时,如果有的输入框不输入,后台应该怎么处理?
    mysql 1449 : The user specified as a definer ('root'@'%') does not exist 解决方法
    C++&&Objective-c
    加载ttf字体
    ios6去除高光效果,和判断iphone或ipad设备
  • 原文地址:https://www.cnblogs.com/bambipai/p/9755513.html
Copyright © 2011-2022 走看看