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

Python实现二叉树

时间:2019-05-16 10:51:56      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:python   后序遍历   前序遍历   ==   obj   先序遍历   code   nod   python实现   

二叉树算法python实现:
1.添加节点
2.广度优先遍历
3.深度优先遍历:先序遍历,中序遍历,后序遍历

# -*- codding:utf-8 -*-
class Node(object):
    """节点"""
    def  __init__(self,item):
        self.elem = item
        self.lchild = None
        self.rchild = None

class Tree(object):
    """二叉树"""
    def __init__(self):
        self.root = None

    def add(self,item):
        node =Node(item)

        if self.root is None:
            self.root = node
            return
        queue = [self.root]

        while queue:
            cur_node =  queue.pop(0)
            if cur_node.lchild is None:
                cur_node.lchild = node
                return
            else :
                queue.append(cur_node.lchild)
            if cur_node.rchild is None:
                cur_node.rchild = node
                return
            else :
                queue.append(cur_node.rchild)

    def bread_travel(self):
        """广度遍历"""
        if self.root is None:
            return
        queue = [self.root]

        while queue:
            cur_node = queue.pop(0)
            print(cur_node.elem,end= " ")
            if cur_node.lchild is not None:
                queue.append(cur_node.lchild)
            if cur_node.rchild is not None:
                queue.append(cur_node.rchild)

    def pre_travel(self,node):
        """前序遍历"""
        if node is None:
            return
        print(node.elem,end = " ")
        self.pre_travel(node.lchild)
        self.pre_travel(node.rchild)

    def mid_travel(self,node):
        """中序遍历"""
        if node is None:
            return
        self.mid_travel(node.lchild)
        print(node.elem,end = " ")
        self.mid_travel(node.rchild)

    def post_travel(self,node):
        """后序遍历"""
        if node is None:
            return
        self.post_travel(node.lchild)
        self.post_travel(node.rchild)
        print(node.elem, end=" ")

if __name__ == "__main__":
    tree = Tree()
    tree.add(0)
    tree.add(1)
    tree.add(2)
    tree.add(3)
    tree.add(4)
    tree.add(5)
    tree.add(6)
    tree.add(7)
    tree.add(8)
    tree.add(9)
    tree.bread_travel()
    print(" ")
    tree.pre_travel(tree.root)
    print(" ")
    tree.mid_travel(tree.root)
    print(" ")
    tree.post_travel(tree.root)

# 0 1 2 3 4 5 6 7 8 9    层次遍历
# 0 1 3 7 8 4 9 2 5 6    前序遍历
# 7 3 8 1 9 4 0 5 2 6    中序遍历
# 7 8 3 9 4 1 5 6 2 0    后序遍历

Python实现二叉树

标签:python   后序遍历   前序遍历   ==   obj   先序遍历   code   nod   python实现   

原文地址:https://blog.51cto.com/10777193/2395373

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