博客
关于我
数据结构 python3 二叉树遍历 前序 中序 后序
阅读量:341 次
发布时间:2019-03-04

本文共 909 字,大约阅读时间需要 3 分钟。

二叉树遍历示例

以下是二叉树的前序、中序和后序遍历示例代码及输出结果。

前序遍历示例

前序遍历的定义是先访问左子树,后访问右子树。以下是代码示例:

def inorderTraversal(self, root: TreeNode) -> List[int]:    res = []    def dfs(root):        if not root:            return        res.append(root.val)        dfs(root.left)        dfs(root.right)    dfs(root)    return res

代码执行后输出结果为:[0, 1, 3, 4, 2]。

中序遍历示例

中序遍历的定义是先访问左子树,后访问右子树。以下是代码示例:

def inorderTraversal(self, root: TreeNode) -> List[int]:    res = []    def dfs(root):        if not root:            return        dfs(root.left)        res.append(root.val)        dfs(root.right)    dfs(root)    return res

代码执行后输出结果为:[3, 1, 4, 0, 2]。

后序遍历示例

后序遍历的定义是先访问左子树,后再访问右子树。以下是代码示例:

def inorderTraversal(self, root: TreeNode) -> List[int]:    res = []    def dfs(root):        if not root:            return        dfs(root.left)        dfs(root.right)        res.append(root.val)    dfs(root)    return res

代码执行后输出结果为:[3, 4, 1, 2, 0]。

转载地址:http://qdce.baihongyu.com/

你可能感兴趣的文章
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.environ 没有设置环境变量
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.removexattr 的 Python 文档——‘*‘(星号)参数是什么意思?
查看>>
os.system 在 Python 中不起作用
查看>>
OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
查看>>
OSCACHE介绍
查看>>