【LEETCODE】257-Binary Tree Paths
2015-11-01 20:16
260 查看
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ self.ans = [] if root is None: return self.ans def dfs(root, path): #if root is None: #外函数已经判断root是否为空了,所以dfs不用再考虑root为空的时候 #return path if root.left == root.right == None: self.ans += path, #一定要加逗号,否则是分开的 if root.left: #self.ans += path dfs(root.left, path + "->" + str(root.left.val)) if root.right: dfs(root.right, path + "->" + str(root.right.val)) #此时path仍然是root的 dfs(root,str(root.val)) return self.ans
相关文章推荐
- iOS 开发 自定义Tabbar
- 个人细小知识点整理
- LeetCode Implement Trie (Prefix Tree) 字典树/前缀树
- FTP上传助手1.1 [免费版]
- Git分支管理策略
- 逻辑运算符 && || ! 的一些理解
- hdu 1800 Flying to the Mars(贪心)
- AJAX请求遭遇未登录和Session失效的解决方案
- 方差分析
- JDK8安装时错误1335的解决
- google镜像
- 拇指接龙游戏升级记录02(Cocos2d-x 3.8.1集成ShareSDK遇到的问题)
- C++局部对象的析构
- [BZOJ1782] [Usaco2010 Feb]slowdown 慢慢游
- 关于OpenNI(1.5/2)和OpenCV的那些事——环境搭建(Windows8.1, 64位系统, VS2012/2013, 华硕XtionProLive)
- 苹果开发 笔记(86)Stack View in xcode 7
- Shell条件测试语句及三种if语句
- hdu 1039 Easier Done Than Said?
- 面对电信运营商HTTP劫持如何是好,投诉太折腾,不如路由器直接屏蔽广告源
- ubuntu14.04下配置使用openCV3.0