Python實現(xiàn)二叉樹的常見遍歷操作總結【7種方法】
本文實例講述了Python實現(xiàn)二叉樹的常見遍歷操作。分享給大家供大家參考,具體如下:
二叉樹的定義:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
二叉樹的前序遍歷
遞歸
def preorder(root,res=[]):
if not root:
return
res.append(root.val)
preorder(root.left,res)
preorder(root.right,res)
return res
迭代
def preorder(root):
res=[]
if not root:
return []
stack=[root]
while stack:
node=stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node,left)
return res
二叉樹的中序遍歷
遞歸
def inorder(root,res=[]):
if not root:
return
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
return res
迭代
def inorder(root):
stack=[]
node=root
res=[]
while stack or node:
while node:
stack.append(node)
node=node.left
node=stack.pop()
res.append(node.val)
node=node.right
return res
二叉樹的后序遍歷
遞歸
def laorder(root,res=[]):
if not root:
return
laorder(root.left,res)
laorder(root.right,res)
res.append(root.val)
return res
迭代
def laorder(root):
stack=[root]
res=[]
while stack:
node=stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res.append(node.val)
return res[::-1]
二叉樹的層次遍歷
迭代
def levelorder(root):
queue=[root]
res=[]
while queue:
node=queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(node.val)
return res
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
分享Pytest fixture參數(shù)傳遞的幾種方式
這篇文章主要分享的是Pytest fixture參數(shù)傳遞的幾種方式,文章基于python的相關資料展開對主題的詳細介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-04-04
Python實現(xiàn)RabbitMQ6種消息模型的示例代碼
這篇文章主要介紹了Python實現(xiàn)RabbitMQ6種消息模型的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
Python類方法__init__和__del__構造、析構過程分析
這篇文章主要介紹了Python類方法__init__和__del__構造、析構過程分析,本文分析了什么時候構造、什么時候析構、成員變量如何處理、Python中的共享成員函數(shù)如何訪問等問題,需要的朋友可以參考下2015-03-03
Python中SOAP項目的介紹及其在web開發(fā)中的應用
這篇文章主要介紹了Python中的SOAP項目及其在web開發(fā)中的應用,本文來自于IBM官方網(wǎng)站技術文檔,需要的朋友可以參考下2015-04-04

