python_lintcode_480二叉树的所有路径_376二叉树的路径和

480二叉树的所有路径

题目

http://www.lintcode.com/zh-cn/problem/binary-tree-paths/

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例
给出下面这棵二叉树:

 。 
   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 __init__(self):
        #路径和列表
        self.path=""
        self.list1=[]
    def binaryTreePaths(self, root):
        # Write your code here
        if root is None:return []
        self.bianli(root,self.path,self.list1)
        return self.list1

    def bianli(self,root,x,y):
        if root is None:return
        x=x+str(root.val)
        if root.right is not None:
            self.bianli(root.right,x+'->',y)
        if root.left is not None:
            self.bianli(root.left,x+'->',y)
        if root.right is None and root.left is None:
            y.append(x)

376二叉树的路径和

题目

http://www.lintcode.com/zh-cn/problem/binary-tree-path-sum/#

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。

一个有效的路径,指的是从根节点到叶节点的路径。

样例
给定一个二叉树,和 目标值 = 5:

>
     1
    / \
   2   4
  / \
 2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]

思路

  • 可根据480得到所有的路径
  • 然后再将路径中满足条件的存入列表组list2
  • 返回list2
  • 问题:路径都是字符串的数组,需要将字符串切割,然后求和,和为target的将字符串以列表的形式存入到列表list2中

代码

"""
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 binary tree
    # @param {int} target an integer
    # @return {int[][]} all valid paths
    def binaryTreePathSum(self, root, target):
        # Write your code here
        path=""
        list1=[]
        list2=[]
        if root is None:return []
        self.bianli(root,path,list1)
        for i in list1:
            i=i.split('->')
            s=target
            m=[]
            for j in i:
                s=s-int(j)
                m.append(int(j))
            if s==0:
                list2.append(m)
        return list2
    #遍历所有的路径和
    def bianli(self,root,x,y):
        if root is None:return
        x=x+str(root.val)
        if root.right is not None:
            self.bianli(root.right,x+'->',y)
        if root.left is not None:
            self.bianli(root.left,x+'->',y)
        if root.right is None and root.left is None:
            y.append(x)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值