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 3 实现定义跨模块的全局变量和使用教程

尽管某些书籍上总是说避免使用全局变量,但是在实际的需求不断变化中,往往定义一个全局变量是最可靠的方法,但是又必须要避免变量名覆盖。 Python 中 global 关键字可以定义一个变量...

python 多维切片之冒号和三个点的用法介绍

python 多维切片之冒号和三个点的用法介绍

初学python和numpy,对在学习多维切片的过程中遇到的问题做个总结。 一维切片就不说了,比较简单,先说下二维的,二维的理解了多维的就简单了。举个例子先建立一个5x5的二维数组 多...

Python+Django在windows下的开发环境配置图解

Python+Django在windows下的开发环境配置图解

1         安装配置开发环境 1.1   准备安装 下载以下软件 Eclipse for...

Python从Excel中读取日期一列的方法

如下所示: import xlrd import datetime file=u"伏特加.xls"#注意读中文文件名稍微处理一下 data=xlrd.open_workbook(...

python学习教程之Numpy和Pandas的使用

python学习教程之Numpy和Pandas的使用

前言 本文主要给大家介绍了关于python中Numpy和Pandas使用的相关资料,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 它们是什么? NumPy是Pytho...