二叉树的所有路径

 1 class Solution:
 2     def binaryTreePaths(self, root: TreeNode) -> List[str]:
 3         def binaryTree(root,path):
 4             if root:
 5                 path+=str(root.val)
 6                 if not root.left and not root.right:
 7                     res.append(path)
 8                 if root.left or root.right: 
 9                     path+="->"
10                     binaryTree(root.left,path)
11                     binaryTree(root.right,path)
12         res=[]
13         binaryTree(root,"")
14         return res

路径总和

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 
 9 
10 class Solution(object):
11     def hasPathSum(self, root, sum):
12         if not root: return False
13         if not root.left and not root.right:
14             return sum == root.val
15         return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
原文地址:https://www.cnblogs.com/lzk-seven/p/13736863.html