溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python實(shí)現(xiàn)二叉樹

發(fā)布時(shí)間:2020-06-27 18:34:30 來源:網(wǎng)絡(luò) 閱讀:1004 作者:小嘉欣 欄目:編程語(yǔ)言

二叉樹算法python實(shí)現(xiàn):
1.添加節(jié)點(diǎn)
2.廣度優(yōu)先遍歷
3.深度優(yōu)先遍歷:先序遍歷,中序遍歷,后序遍歷

# -*- codding:utf-8 -*-
class Node(object):
    """節(jié)點(diǎn)"""
    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    后序遍歷
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI