好湿?好紧?好多水好爽自慰,久久久噜久噜久久综合,成人做爰A片免费看黄冈,机机对机机30分钟无遮挡

主頁 > 知識庫 > 教你如何使用Python實現二叉樹結構及三種遍歷

教你如何使用Python實現二叉樹結構及三種遍歷

熱門標簽:老人電話機器人 地圖標注視頻廣告 北京電信外呼系統靠譜嗎 梅州外呼業務系統 百度地圖標注位置怎么修改 高德地圖標注是免費的嗎 洪澤縣地圖標注 大連crm外呼系統 無錫客服外呼系統一般多少錢

一:代碼實現

class TreeNode:
    """節點類"""
    def __init__(self, mid, left=None, right=None):
        self.mid = mid
        self.left = left
        self.right = right


# 樹類
class Tree:
    """樹類"""
    def __init__(self, root=None):
        self.root = root

    def add(self, item):
        # 將要添加的數據封裝成一個node結點
        node = TreeNode(item)
        if not self.root:
            self.root = node
            return
        queue = [self.root]
        while queue:
            cur = queue.pop(0)
            if not cur.left:
                cur.left = node
                return
            else:
                queue.append(cur.left)

            if not cur.right:
                cur.right = node
                return
            else:
                queue.append(cur.right)
               
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)

二:遍歷

在上述樹類代碼基礎上加遍歷函數,基于遞歸實現。

先序遍歷:

先序遍歷結果是:0 -> 1 -> 3 -> 4 -> 2 -> 5 -> 6

# 先序遍歷
    def preorder(self, root, result=[]):
        if not root:
            return
        result.append(root.mid)
        self.preorder(root.left, result)
        self.preorder(root.right, result)
        return result
        
print("先序遍歷")
print(tree.preorder(tree.root))
"""
先序遍歷
[0, 1, 3, 4, 2, 5, 6]
"""

中序遍歷:

中序遍歷結果是:3 -> 1 -> 4 -> 0 -> 5 -> 2 -> 6

# 中序遍歷
    def inorder(self, root, result=[]):
        if not root:
            return result
        self.inorder(root.left, result)
        result.append(root.mid)
        self.inorder(root.right, result)
        return result
        
print("中序遍歷")
print(tree.inorder(tree.root))
"""
中序遍歷
3, 1, 4, 0, 5, 2, 6]
"""

后續遍歷

后序遍歷結果是:3 -> 4 -> 1 -> 5 -> 6 -> 2 -> 0

# 后序遍歷
    def postorder(self, root, result=[]):
        if not root:
            return result
        self.postorder(root.left, result)
        self.postorder(root.right, result)
        result.append(root.mid)

        return result
        
print("后序遍歷")
print(tree.postorder(tree.root))
"""
后序遍歷
[3, 4, 1, 5, 6, 2, 0]
"""

到此這篇關于教你如何使用Python實現二叉樹結構及三種遍歷的文章就介紹到這了,更多相關Python實現二叉樹結構及三種遍歷內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Python數據結構與算法之二叉樹結構定義與遍歷方法詳解
  • Python實現二叉樹結構與進行二叉樹遍歷的方法詳解

標簽:清遠 吉林 長春 怒江 安慶 泉州 岳陽 洛陽

巨人網絡通訊聲明:本文標題《教你如何使用Python實現二叉樹結構及三種遍歷》,本文關鍵詞  教你,如何,使用,Python,實現,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《教你如何使用Python實現二叉樹結構及三種遍歷》相關的同類信息!
  • 本頁收集關于教你如何使用Python實現二叉樹結構及三種遍歷的相關信息資訊供網民參考!
  • 推薦文章