描述
给一棵二叉树,找出从根节点到叶子节点的所有路径。
样例
样例 1:
输入:{1,2,3,#,5}
输出:["1->2->5","1->3"]
解释:
1
/ \
2 3
\
5
样例 2:
输入:{1,2}
输出:["1->2"]
解释:
1
/
2
这一题使用分治法来做会比较好,什么叫分治法呢?就是把一个复杂的问题拆分,在拆分完成后再merge。
比如说这一题就可以拆分,首先找规律,对于每一个非叶结点,它到叶结点的路径是 自己+'->'+左子树路径 和 自己+'->'+右子树路径。这样的话就可以把问题拆分为左子树和右子树,只需要在得到左右子树的结果后进行merge。同时要注意对于叶结点的处理是不一样的。
代码:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
def paths(root):
if root is None:
return ''
# 叶子结点
if root.left is None and root.right is None:
return [str(root.val)]
# 拆分左右子树结果
leftresult=paths(root.left)
rightresult=paths(root.right)
# merge结果
result=[]
for i in leftresult:
result.append(str(root.val)+'->'+i)
for i in rightresult:
result.append(str(root.val) + '->' + i)
return result
if root is None:
return []
final=paths(root)
return final
Tree = TreeNode(1)
Tree.left = TreeNode(2)
Tree.left.right =TreeNode(5)
Tree.right = TreeNode(3)
s = Solution()
print(s.binaryTreePaths(Tree))