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程序设计有所帮助。

相关文章

python3编写ThinkPHP命令执行Getshell的方法

python3编写ThinkPHP命令执行Getshell的方法

加了三个验证漏洞以及四个getshell方法 # /usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: Morker #...

通过celery异步处理一个查询任务的完整代码

今天介绍通过celery实现一个异步任务。有这样一个需求,前端发起一个查询的请求,但是发起查询后,查询可能不会立即返回结果。这时候,发起查询后,后端可以把这次查询当作一个task,并立即...

如何用Python来搭建一个简单的推荐系统

在这篇文章中,我们会介绍如何用Python来搭建一个简单的推荐系统。 本文使用的数据集是MovieLens数据集,该数据集由明尼苏达大学的Grouplens研究小组整理。它包含1,10和...

Python常用库推荐

IPython + ptpython,完美体验 首先是安装 pip install ipython ptpython 然后使用 ptipython 有什么好处 1. IPython...

python实现定时压缩指定文件夹发送邮件

工作中每天需要收集部门内的FR文件,发送给外部部门的同事帮忙上传,这么发了有大半年,昨天亮光一闪,为什么不做成自动化呢,于是用python实现了整个流程,今天体验了一下真是美滋滋。 代码...