码迷,mamicode.com
首页 > 编程语言 > 详细

Python 创建二叉树 & 遍历二叉树(前序、中序、后续)

时间:2021-06-17 17:24:02      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:evel   遍历   pytho   color   not   middle   order   value   shift   


 

二叉树的从上到下的打印代码参考:

print binary tree level by level in python

主要是为了更加清晰的看到二叉树的结构

 

再发一遍参考代码的网址:

https://stackoverflow.com/questions/34012886/print-binary-tree-level-by-level-in-python

 


 

创建二叉树 & 遍历二叉树(前序、中序、后续):

#!/usr/bin/env python
# coding: utf-8


# 树的节点(值+左节点+右节点)
class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left  = left
        self.right = right


# 二叉树
class BinaryTree:
    # 初始化
    def __init__(self, root, tree_dict):
        # 获取所有节点
        nodes_dict = {node_val: TreeNode(node_val) for node_val in tree_dict}
        # 将每个节点都连起来,也就是创建二叉树
        for node_value, (lchild_value, rchild_value) in tree_dict.items():
            treenode = nodes_dict[node_value]
            if lchild_value:
                treenode.left = nodes_dict[lchild_value]
            if rchild_value:
                treenode.right = nodes_dict[rchild_value]
        # 规定二叉树的根节点
        self.root = nodes_dict[root]

    # 获取二叉树的高度
    # def getHeight(self):
    #     def maxHeight(node):
    #         if not node:
    #             return 0
    #         return max(maxHeight(node.left), maxHeight(node.right)) + 1
    #     return maxHeight(self.root)

    # 计算二叉树的节点的数量
    # def countNodes(self):
    #     def nodesNumber(node):
    #         if not node:
    #             return 0
    #         return nodesNumber(node.left) + nodesNumber(node.right) + 1
    #     return nodesNumber(self.root)

    # 二叉树从上到下打印(代码参考了他人的)
    # References Website:
    # https://stackoverflow.com/questions/34012886/print-binary-tree-level-by-level-in-python
    def printTreeStructure(self):
        def getStructure(node):
            if node.right is None and node.left is None:
                line = %s % node.value
                width = len(line)
                height = 1
                middle = width // 2
                return [line], width, height, middle
            if node.right is None:
                lines, n, p, x = getStructure(node.left)
                s = %s % node.value
                u = len(s)
                first_line = (x + 1) *   + (n - x - 1) * _ + s
                second_line = x *   + / + (n - x - 1 + u) *  
                shifted_lines = [line + u *   for line in lines]
                return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2
            if node.left is None:
                lines, n, p, x = getStructure(node.right)
                s = %s % node.value
                u = len(s)
                first_line = s + x * _ + (n - x) *  
                second_line = (u + x) *   + \\ + (n - x - 1) *  
                shifted_lines = [u *   + line for line in lines]
                return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2
            left, n, p, x = getStructure(node.left)
            right, m, q, y = getStructure(node.right)
            s = %s % node.value
            u = len(s)
            first_line = (x + 1) *   + (n - x - 1) * _ + s + y * _ + (m - y) *  
            second_line = x *   + / + (n - x - 1 + u + y) *   + \\ + (m - y - 1) *  
            if p < q:
                left += [n *  ] * (q - p)
            elif q < p:
                right += [m *  ] * (p - q)
            zipped_lines = zip(left, right)
            lines = [first_line, second_line] + [a + u *   + b for a, b in zipped_lines]
            return lines, n + m + u, max(p, q) + 2, n + u // 2
        # print tree structure
        print(二叉树的结构为: )
        lines, *_ = getStructure(self.root)
        for line in lines:
            print(line)
        print()

    # 前序遍历
    def preorderTraversal(self):
        print(前序遍历: , end=‘‘)
        # 此函数会递归调用自身,每次的节点node都不同,所以使用函数嵌套,更加清晰明了
        def preorder(node):
            if node:
                print(node.value, end=‘‘)
                preorder(node.left)
                preorder(node.right)
        # 传入根节点
        preorder(self.root)
        print()

    def inorderTraversal(self):
        print(中序遍历: , end=‘‘)
        def inorder(node):
            if node:
                inorder(node.left)
                print(node.value, end=‘‘)
                inorder(node.right)
        inorder(self.root)
        print()

    def postorderTraversal(self):
        print(后序遍历: , end=‘‘)
        def postorder(node):
            if node:
                postorder(node.left)
                postorder(node.right)
                print(node.value, end=‘‘)
        postorder(self.root)
        print()



if __name__ == __main__:
    # 输入(支持字母和数字):
    # 1. 根节点
    # 2. 每个节点和其对应的子节点(若字节点为空,则输入None)
    root = A
    tree_dict = {
        A: (B ,  C),
        B: (D , None),
        C: (F ,  K),
        D: (None,  G),
        F: (None, None),
        G: (None, None),
        K: (None,    2),
         2 : (None, None),
    }

    # 构建二叉树(实例化类)
    btree = BinaryTree(root, tree_dict)

    # 打印二叉树
    btree.printTreeStructure()
    btree.preorderTraversal()
    btree.inorderTraversal()
    btree.postorderTraversal()

 

输出:

二叉树的结构为: 
   A_   
  /  \  
 _B  C  
/   / \ 
D   F K 
 \      G     2

前序遍历: ABDGCFK2
中序遍历: DGBAFCK2
后序遍历: GDBF2KCA

 


 

Python 创建二叉树 & 遍历二叉树(前序、中序、后续)

标签:evel   遍历   pytho   color   not   middle   order   value   shift   

原文地址:https://www.cnblogs.com/Alan-LJP/p/14893483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!