博客
关于我
数据结构 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/

你可能感兴趣的文章
poj 2763 Housewife Wind
查看>>
Qt笔记——模型/视图MVD 文件目录浏览器软件
查看>>
POJ 2892 Tunnel Warfare(树状数组+二分)
查看>>
poj 2965 The Pilots Brothers' refrigerator-1
查看>>
poj 3026( Borg Maze BFS + Prim)
查看>>
POJ 3041 - 最大二分匹配
查看>>
POJ 3041 Asteroids(二分匹配模板题)
查看>>
Qt笔记——标准文件对话框QFileDialog
查看>>
poj 3083 Children of the Candy Corn
查看>>
POJ 3083 Children of the Candy Corn 解题报告
查看>>
POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
查看>>
Qt笔记——控件总结
查看>>
poj 3262 Protecting the Flowers 贪心
查看>>
poj 3264(简单线段树)
查看>>
Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
查看>>
poj 3277 线段树
查看>>
POJ 3349 Snowflake Snow Snowflakes
查看>>
POJ 3411 DFS
查看>>
poj 3422 Kaka's Matrix Travels (费用流 + 拆点)
查看>>
Qt笔记——官方文档全局定义(二)Functions函数
查看>>