欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)的二叉樹定義與遍歷算法實例

 更新時間:2017年06月30日 10:09:09   作者:ZHOU YANG  
這篇文章主要介紹了python實現(xiàn)的二叉樹定義與遍歷算法,結(jié)合具體實例形式分析了基于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程序設計有所幫助。

相關文章

最新評論