Python实现二叉树的常见遍历操作总结【7种方法】

yipeiwu_com5年前Python基础

本文实例讲述了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 处理 JSON 格式的数据

如果你不希望从头开始创造一种数据格式来存放数据,JSON 是一个很好的选择。如果你对 Python 有所了解,就更加事半功倍了。下面就来介绍一下如何使用 Python 处理 JSON 数...

Python使用设计模式中的责任链模式与迭代器模式的示例

Python使用设计模式中的责任链模式与迭代器模式的示例

责任链模式 责任链模式:将能处理请求的对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理请求为止,避免请求的发送者和接收者之间的耦合关系。 #encoding=utf-8...

Python程序中使用SQLAlchemy时出现乱码的解决方案

今天对clubot进行了升级, 但是导入数据后中文乱码, 一开是找资料说是在创建引擎的时候添加编码信息: engine = create_engine("mysql://root:@...

Python中返回字典键的值的values()方法使用

 values()方法返回给定的字典中所有可用值的列表。 语法 以下是values()方法的语法: dict.values() 参数   &...

Python实现Tab自动补全和历史命令管理的方法

本文实例讲述了Python实现Tab自动补全和历史命令管理的方法。分享给大家供大家参考。具体分析如下: Python的startup文件,即环境变量 PYTHONSTARTUP 对应的文...