python實現(xiàn)的二叉樹定義與遍歷算法實例
本文實例講述了python實現(xiàn)的二叉樹定義與遍歷算法。分享給大家供大家參考,具體如下:
初學(xué)python,需要實現(xiàn)一個決策樹,首先實踐一下利用python實現(xiàn)一個二叉樹數(shù)據(jù)結(jié)構(gòu)。建樹的時候做了處理,保證建立的二叉樹是平衡二叉樹。
# -*- 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
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python零基礎(chǔ)入門學(xué)習(xí)之輸入與輸出
在之前的編程中,我們的信息打印,數(shù)據(jù)的展示都是在控制臺(命令行)直接輸出的,信息都是一次性的沒有辦法復(fù)用和保存以便下次查看,今天我們將學(xué)習(xí)Python的輸入輸出,解決以上問題2019-04-04
安裝pytorch報錯torch.cuda.is_available()=false問題的解決過程
最近想用pytorch,因此裝了pytorch,但是碰到了問題,下面這篇文章主要給大家介紹了關(guān)于安裝pytorch報錯torch.cuda.is_available()=false問題的解決過程,需要的朋友可以參考下2022-05-05
Python使用pandas實現(xiàn)對數(shù)據(jù)進(jìn)行特定排序
在數(shù)據(jù)分析和處理過程中,排序是一項常見而重要的操作,本文將詳細(xì)介紹如何利用pandas對數(shù)據(jù)進(jìn)行特定排序,包括基本排序、多列排序、自定義排序規(guī)則等方面的內(nèi)容,需要的可以了解下2024-03-03
python實現(xiàn)查詢蘋果手機(jī)維修進(jìn)度
這篇文章主要介紹了python實現(xiàn)查詢蘋果手機(jī)維修進(jìn)度,這里用到了最重要的一個知識是python中如何設(shè)置cookie支持以及開啟調(diào)試模式,需要的朋友可以參考下2015-03-03

