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

来源:互联网 发布:iapp制作文字游戏源码 编辑:程序博客网 时间:2024/06/16 14:31

480二叉树的所有路径

题目

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

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

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

 。    1 /   \2     3 \  5

所有根到叶子的路径为:

[  "1->2->5",  "1->3"]

思路

  • 遍历二叉树,将满足self.left is None and self.right is None的字符串放入列表中
  • 最后返回这个列表
    参考博客:http://blog.csdn.net/yurenguowang/article/details/77678894

代码

"""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)
原创粉丝点击