本文實例講述了Python實現二叉樹的常見遍歷操作。分享給大家供大家參考,具體如下:
二叉樹的定義:
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程序設計有所幫助。
新聞熱點
疑難解答