python實現(xiàn)的二叉樹定義與遍歷算法實例
本文實例講述了python實現(xiàn)的二叉樹定義與遍歷算法。分享給大家供大家參考,具體如下:
初學python,需要實現(xiàn)一個決策樹,首先實踐一下利用python實現(xiàn)一個二叉樹數(shù)據(jù)結(jié)構。建樹的時候做了處理,保證建立的二叉樹是平衡二叉樹。
# -*- coding: utf-8 -*- from collections import deque class Node: def __init__(self,val,left=None,right=None): self.val=val self.left=left self.right=right #setter and getter def get_val(self): return self.val def set_val(self,val): self.val=val def get_left(self): return self.left def set_left(self,left): self.left=left def get_right(self): return self.right def set_right(self,right): self.right=right class Tree: def __init__(self,list): list=sorted(list) self.root=self.build_tree(list) #遞歸建立平衡二叉樹 def build_tree(self,list): l=0 r=len(list)-1 if(l>r): return None if(l==r): return Node(list[l]) mid=(l+r)/2 root=Node(list[mid]) root.left=self.build_tree(list[:mid]) root.right=self.build_tree(list[mid+1:]) return root #前序遍歷 def preorder(self,root): if(root is None): return print root.val self.preorder(root.left) self.preorder(root.right) #后序遍歷 def postorder(self,root): if(root is None): return self.postorder(root.left) self.postorder(root.right) print root.val #中序遍歷 def inorder(self,root): if(root is None): return self.inorder(root.left) print root.val self.inorder(root.right) #層序遍歷 def levelorder(self,root): if root is None: return queue =deque([root]) while(len(queue)>0): size=len(queue) for i in range(size): node =queue.popleft() print node.val if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) list=[1,-1,3,4,5] tree=Tree(list) print '中序遍歷:' tree.inorder(tree.root) print '層序遍歷:' tree.levelorder(tree.root) print '前序遍歷:' tree.preorder(tree.root) print '后序遍歷:' tree.postorder(tree.root)
輸出:
中序遍歷 -1 1 3 4 5 層序遍歷 3 -1 4 1 5 前序遍歷 3 -1 1 4 5 后序遍歷 1 -1 5 4 3
建立的二叉樹如下圖所示:
PS:作者的github: https://github.com/zhoudayang
更多關于Python相關內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python數(shù)據(jù)結(jié)構樹和二叉樹簡介
這篇文章主要介紹了python數(shù)據(jù)結(jié)構樹和二叉樹簡介,需要的朋友可以參考下2014-04-04Python中實現(xiàn)參數(shù)類型檢查的簡單方法
這篇文章主要介紹了Python中實現(xiàn)參數(shù)類型檢查的簡單方法,本文講解使用裝飾器實現(xiàn)參數(shù)類型檢查并給出代碼實例,需要的朋友可以參考下2015-04-04教你用Python查看茅臺股票交易數(shù)據(jù)的詳細代碼
CSV是以逗號分隔數(shù)據(jù)項(也被稱為字段)的數(shù)據(jù)交換格式,主要應用于電子表格和數(shù)據(jù)庫之間的數(shù)據(jù)交換,本文給大家介紹下用Python查看茅臺股票交易數(shù)據(jù)的詳細代碼,感興趣的朋友一起看看吧2022-03-03python如何發(fā)送xml格式請求數(shù)據(jù)
這篇文章主要介紹了python如何發(fā)送xml格式請求數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06