Leetcode-113Path Sum II

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

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

题解:

输入一个二叉树和一个整数 sum,输出满足从二叉树的根到叶节点的路径值之和等于 sum 的所有路径。
对于上面给出的例子:

Leetcode-113Path Sum II_第1张图片
image.png

sum = 22;
从根节点到叶节点的路径:
5->4->11->7:value = 5 + 4 + 11 + 7 > sum;
5->4->11->2:value == sum; 满足条件
5->8->13:value = 5 + 8 + 13 > sum;
5->8->4->5:value = 5 + 8 + 4 + 5 == sum; 满足条件
5->8->4->1:value = 5 + 8 + 4 + 1 < sum;
所以输出:[ [5,4,11,2], [5,8,4,5] ]
不难看出,这是一个递归的问题;
满足路径值等于 sum 且 该节点为叶节点时,说明该路径符合条件;

My Solution(C/C++)

#include 
#include 
#include 

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector> pathSum(TreeNode *root, int sum) {
        vector path;
        vector> result;
        save_path(root, 0, sum, path, result);
        return result;
    }
private:
    void save_path(TreeNode *root, int value, int sum, vector &path, vector> &result) {
        //if (!root || value > sum) {  //不能剪枝,因为存在根节点为-2,sum为-5这类情况;
            //if (value == sum) {  // 不能放到这里,因为会对叶节点的左右节点各判断一次,所以会存两次相同的路径;
            //  result.push_back(path);
            //}
        //  return;
        //}
        if (!root) {
            return;
        }
        value += root->val;
        path.push_back(root->val);
        if (!root->left && !root->right && value == sum) {
            result.push_back(path);
        }
        save_path(root->left, value, sum, path, result);
        //value -= root->val;  //叶节点的父节点11在未加上右叶节点值前,就会先删除本身的val;
        //path.pop_back();
        save_path(root->right, value, sum, path, result);
        //value -= root->val;  //此时,由于形参的value不是引用传值,该层的递归结束,会释放当层的自动存储变量 value;
        path.pop_back();  //  //此时,由于形参的path是引用传值,该层的递归结束,path里的值还在,所以需要删除不符合的节点;
    }
};
int main() {
    TreeNode a(5);
    TreeNode b(4);
    TreeNode c(8);
    TreeNode d(11);
    TreeNode e(13);
    TreeNode f(4);
    TreeNode g(7);
    TreeNode h(2);
    TreeNode i(5);
    TreeNode j(1);
    a.left = &b;
    b.left = &d;
    d.left = &g;
    d.right = &h;
    a.right = &c;
    c.left = &e;
    c.right = &f;
    f.left = &i;
    f.right = &j;
    Solution s;
    vector> result;
    result = s.pathSum(&a, 22);
    for (int i = 0; i < result.size(); i++) {
        for (int j = 0; j < result[i].size(); j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }
    return 0;
}

结果

5 4 11 2
5 8 4 5

My Solution(Python)

# 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, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        result = []
        self.Sum_judge(root, 0, sum, [], result)
        return result

    def Sum_judge(self, root, cur_sum, sum, temp, result):
        if root == None:
            return
        temp.append(root.val)
        cur_sum += root.val
        if cur_sum == sum and root.left == None and root.right == None:
            temp_data = temp.copy()
            result.append(temp_data)
        self.Sum_judge(root.left, cur_sum, sum, temp, result)
        self.Sum_judge(root.right, cur_sum, sum, temp, result)
        temp.pop()
        

你可能感兴趣的:(Leetcode-113Path Sum II)