zoukankan      html  css  js  c++  java
  • 二叉树前序遍历&后续遍历&中序遍历

    class BiTNode():
        def __init__(self):
            self.data = None
            self.lchild = None
            self.rchild = None
    
    # 方法功能:把有序数组转为二叉树
    def arraytotree(arr,start,end):
        root = None
        if end >= start:
            root = BiTNode()
            mid = (start+end+1)//2
            # 树的根节点为数组中间的元素
            root.data = arr[mid]
            print(root.data)
            # 递归的用左半部分数组构成 root 的左子树
            root.lchild = arraytotree(arr,start,mid-1)
            # 递归地用右半部分数组构成 root 的右子树
            root.rchild = arraytotree(arr,mid+1,end)
        else:
            root = None
        return root
    
    # 用中序遍历的方法打印出二叉树结点的内容
    def printTreeMidOrder(root):
        if root == None:
            return None
        #遍历root结点的左子树
        if root.lchild != None:
            printTreeMidOrder(root.lchild)
        #遍历root结点
        print(root.data,end=' ')   #先从左边遍历
        #遍历 root 的右子树
        if root.rchild != None:
            printTreeMidOrder(root.rchild)
    
    #前序遍历
    def printTreePreOrder(root):
        if root == None:
            return None
        #遍历root结点
        print(root.data,end=' ')
        #遍历root结点的左子树
        if root.lchild != None:
            printTreeMidOrder(root.lchild)
        #遍历 root 的右子树
        if root.rchild != None:
            printTreeMidOrder(root.rchild)
    
    #后序遍历
    def printTreeAfterOrder(root):
        if root == None:
            return None
        #遍历root结点的左子树
        if root.lchild != None:
            printTreeMidOrder(root.lchild)
        #遍历 root 的右子树
        if root.rchild != None:
            printTreeMidOrder(root.rchild)
        #遍历root结点
        print(root.data,end=' ')   
    
    arr = [1,2,3,4,5,6,7,8,9,10]
    print("数组:",end='')
    i = 0
    while i < len(arr):
        print(arr[i],end = ' ')
        i += 1
    print()
    root = arraytotree(arr,0,len(arr)-1)
    print("转换成树的中序遍历为:",end='')
    printTreeMidOrder(root)
  • 相关阅读:
    [模板]大数加法
    HDU 1848 Fibonacci again and again
    同时安装了Python2和Python3时的pip使用
    UPC-2785 One-Way Roads(最大流建图)
    UPC-2784 Model Railroad(最小生成树)
    【ICPC 2017 Daejeon】UPC-9312 Game Map(dfs)
    【ICPC 2015 Shenyang】UVALive
    【ICPC 2015 Shenyang 】UPC-9254 MEETING(最短路&虚点建图)
    UPC-9264 Chip Factory(01字典树)
    【ICPC 2018 Malaysia】UPC-9302 ELI'S CURIOUS MIND(递推)
  • 原文地址:https://www.cnblogs.com/sunny0824/p/13677606.html
Copyright © 2011-2022 走看看