【剑指offer】面试题34. 二叉树中和为某一值的路径

题目描述

面试题34. 二叉树中和为某一值的路径

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
 
示例:
给定如下二叉树,以及目标和 sum = 22,
              5
             /
            4   8
           /   /
          11  13  4
         /      /
        7    2  5   1

返回:
[
   [5,4,11,2],
   [5,8,4,5]
]
 

分析

思路很简单,可就是自己写不出代码咋整...

先序遍历,依次加和当前节点val(或减,无所谓),满足和为target以及最后一个节点是叶子结点时返回。

5 4 11 7 结束后,当前记录的列表不符合要求,应该弹出7 pop然后访问11的右子树2,判断不符合继续pop2 

抄了解法2,更好懂一点

解题

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res=[]
        temp=[]
        def recur(root,target):
            if(not root):
                return []
            temp.append(root.val)
            target -=root.val
            if target ==0 and not root.left and not root.right:
                res.append(temp[:])#深拷贝,因为每次不清空
            recur(root.left, target)
            recur(root.right, target)
            temp.pop()
        recur(root, sum)
        return res

 2.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
        # write code here
        if root == None :
            return([])
        res = []
        def dfs(root,road):
            if root.left==None and root.right==None:
                if sum(road)==target:
                    res.append(road)
                return 
            if root.left != None: dfs(root.left, road+[root.left.val])
            if root.right != None: dfs(root.right, road+[root.right.val])
        
        dfs(root,[root.val])
        return(res)
原文地址:https://www.cnblogs.com/fuj905/p/12917659.html