[LintCode 480] 二叉树的所有路径(Python)
来源:互联网 发布:钢琴联系软件 编辑:程序博客网 时间:2024/06/06 14:08
题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
样例
给出下面这棵二叉树:
1 / \2 3 \ 5
所有根到叶子的路径为:
[ "1->2->5", "1->3"]
思路
递归法。用一个数组来存储路径。然后递归遍历左右子树,把所有路径加进来。递归结束的条件是遇到叶节点,即左右节点都为空,然后把当前路径加入待返回的数组中。
代码
"""Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""class Solution: # @param {TreeNode} root the root of the binary tree # @return {List[str]} all root-to-leaf paths def binaryTreePaths(self, root): # Write your code here path = '' res = [] self.TreePathsHelper(root, path, res) return res def TreePathsHelper(self, root, path, res): if root is None: return path += str(root.val) if root.left is not None: self.TreePathsHelper(root.left, path + '->', res) if root.right is not None: self.TreePathsHelper(root.right, path + '->', res) if root.left is None and root.right is None: res.append(path)
阅读全文
0 0
- [LintCode 480] 二叉树的所有路径(Python)
- LintCode 480-二叉树的所有路径
- LintCode- 二叉树的所有路径
- lintcode----二叉树的所有路径
- lintcode,二叉树的所有路径
- lintcode二叉树的所有路径
- LintCode | 480. 二叉树的所有路径
- LintCode 二叉树的所有路径
- 二叉树的所有路径-LintCode
- LintCode-二叉树的所有路径
- lintcode二叉树的所有路径
- lintcode 二叉树的所有路径
- LintCode 二叉树的所有路径
- lintcode--二叉树的所有路径
- [LintCode]480.二叉树的所有路径
- 二叉树的所有路径-LintCode
- lintcode(480)——二叉树的所有路径
- lintcode binary-tree-paths 二叉树的所有路径
- ORA-16038: log 3 sequence# 4 cannot be archived
- 关闭 sp_OACreate 与 xp_cmdshell
- 2selenium+python 基础知识
- Java线程创建的两种方式
- 流程图符号及流程图的例子
- [LintCode 480] 二叉树的所有路径(Python)
- Cpp-虚函数
- Android---RecyclerView之简单瀑布流实现
- Java安全学习笔记(十)-输出流的加密和解密
- Orange内的associate rule例子
- C语言中printf用%d输出float类型数据,或以%f输出int型数据的结果
- 浅谈SOPC中的“system_id”和“time_stamp”不符的原因和解决
- Hive笔记整理之——文件存储格式
- UVA