杰网资源 Design By www.escxy.com
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
标签:
Python,二叉树,遍历
杰网资源 Design By www.escxy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
杰网资源 Design By www.escxy.com
暂无评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。