美文网首页
二叉树中和为某一值的路径

二叉树中和为某一值的路径

作者: GoDeep | 来源:发表于2018-03-30 21:58 被阅读0次

题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

# -*- coding:utf-8 -*-
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
        
class Solution:
    def FindPath(self, root, expectNumber):
        # write code here
        if not root: return []
        res, t = [], []
        def dfs(root):
            if not root:
                if sum(t)==expectNumber: res.append(list(t))
                return
                
            t.append(root.val)
            dfs(root.left)
            dfs(root.right)
            t.pop()
        
        dfs(root)
        return res[::2]
        

相关文章

网友评论

      本文标题:二叉树中和为某一值的路径

      本文链接:https://www.haomeiwen.com/subject/nprwcftx.html