113. 路径总和 II-二叉树的中序遍历

问题描述

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

5
/
4 8
/ /
11 13 4
/ /
7 2 5 1
返回:

[
[5,4,11,2],
[5,8,4,5]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii

解答

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

二叉树的中序遍历。

'''
class Solution(object):
    def pathSum(self, root, sum):
        if root == None:
            return []
        result = []
        def backtrack(root, arr, count):
            if root.left == None and root.right == None:
                arr.append(root.val)
                if count + root.val == sum:
                    result.append([])
                    result[-1].extend(arr)
                arr.pop()
                return
            if root.left != None:
                arr.append(root.val)
                count += root.val
                backtrack(root.left, arr, count)
                count -= root.val
                arr.pop()
            if root.right != None:
                arr.append(root.val)
                count += root.val
                backtrack(root.right, arr, count)
                count -= root.val
                arr.pop()
        backtrack(root, [], 0)
        return result
原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13246541.html