zoukankan      html  css  js  c++  java
  • 二叉树

    # 定义一个类 创建一个二叉树
    class Btree:
        def __init__(self,data):
            self.data = data
            self.lchild = None
            self.rchild = None
            
    a = Btree("A")
    b = Btree("B")
    c = Btree("C")
    d = Btree("D")
    e = Btree("E")
    f = Btree("F")
    
    root = a
    a.lchild = b
    a.rchild = c
    b.lchild = d
    b.rchild = e
    c.lchild = f
    # 广度优先遍历
    def
    level_order(root): if not root or root.data is None: return [] else: my_queue=[] re_queue=[] my_queue.append(root) while my_queue: cur_node = my_queue.pop(0) re_queue.append(cur_node.data) if cur_node.lchild: my_queue.append(cur_node.lchild) if cur_node.rchild: my_queue.append(cur_node.rchild) return re_queue level_order(root) # ['A', 'B', 'C', 'D', 'E', 'F']
    
    
    # 前序遍历
    def pre_order(root):
        if root:
            print(root.data, end=" ")
            pre_order(root.lchild)
            pre_order(root.rchild)
            
    pre_order(root)
    
    # A B D E C F
    # 中序遍历
    # 每次从左孩子返回  打印该节点  
    # 先递归左孩子,再输出自己,再递归右孩子. 意味着只有当每一个节点的左孩子全部打印,再打印自己,最后打印右孩子
    
    def mid_order(root): 
        if root:
            mid_order(root.lchild)
            print(root.data,end=" ")
            mid_order(root.rchild)
            
    mid_order(root)
    # D B E A F C
    # 后序遍历
    # 先递归左子树,在递归右子树,最后输出节点自己.  (左子树,右子树,节点)
    
    def post_order(root):
        if root:
            post_order(root.lchild)
            post_order(root.rchild)
            print(root.data,end=" ")
    post_order(root)
    
    # D E B F C A
  • 相关阅读:
    获取文件mime类型
    PHP的CURL
    PHP curl报错“Problem (2) in the Chunked-Encoded data”解决方案
    MySQL中的group_concat函数
    MYSQL批量修改表前缀与表名sql语句
    ubuntu18.04 无法连接有线
    ffmpeg接收udp输入的h264文件流,推流到rtmp服务器
    nginx-rtmp
    tf.image.crop_and_resize
    tf.reduce_sum
  • 原文地址:https://www.cnblogs.com/kenD/p/11088967.html
Copyright © 2011-2022 走看看