python二叉树遍历算法_分享python实现的二叉树定义与遍历
這篇文章主要介紹了python實(shí)現(xiàn)的二叉樹定義與遍歷算法,結(jié)合具體實(shí)例形式分析了基于Python定義的二叉樹及其常用遍歷操作實(shí)現(xiàn)技巧,需要的朋友可以參考下
本文實(shí)例講述了python實(shí)現(xiàn)的二叉樹定義與遍歷算法。分享給大家供大家參考,具體如下:
初學(xué)python,需要實(shí)現(xiàn)一個(gè)決策樹,首先實(shí)踐一下利用python實(shí)現(xiàn)一個(gè)二叉樹數(shù)據(jù)結(jié)構(gòu)。建樹的時(shí)候做了處理,保證建立的二叉樹是平衡二叉樹。
# -*- 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
建立的二叉樹如下圖所示:
總結(jié)
以上是生活随笔為你收集整理的python二叉树遍历算法_分享python实现的二叉树定义与遍历的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 超时空炮在哪得
- 下一篇: python减少内存_如何降低 Pyth