[CareerCup] 4.9 All Paths Sum 所有路径和

4.9 You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum to a given value. The path does not need to start or end at the root or a leaf.

这道题给我们一个二叉树,让我们找出所有的路径,其和为给定的值,而且说了路径不必起始于根,终止于叶节点,但必须是向下的一条路径。LeetCode中相似的题有Path Sum 二叉树的路径和Path Sum II 二叉树路径之和之二。但是那题要找的是起始于根,终止于叶节点的路径,而这题是找出所有的路径。所以要稍稍复杂一些。这题的解题思路是先求出给定二叉树的深度,关于求二叉树的深度可以参见我之前的博客Maximum Depth of Binary Tree 二叉树的最大深度。然后我们建立一个大小为树的最大深度的一维向量,用来存每一层路径上的值。然后从第一层开始递归,对每一个节点,更新当前层的path,然后从此层向第一层遍历,将path各层值加起来,如果等于sum的话,就把这道路径打印或者保存起来,然后在对当前节点的左右子节点分别递归调用。时间复杂度为O(nlgn),空间复杂度为O(lgn),参见代码如下:

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        if (!root) return vector<vector<int> >();
        int depth = getDepth(root);
        vector<vector<int> > res;
        vector<int> path(depth, INT_MIN);
        pathSumDFS(root, sum, 0, path, res);
        return res;
    }
    void pathSumDFS(TreeNode *root, int sum, int level, vector<int> &path, vector<vector<int> > &res) {
        if (!root) return;
        path[level] = root->val;
        int t = 0;
        for (int i = level; i >= 0; i--) {
            t += path[i];
            if (t == sum) {
                savePath(path, i, level, res);
            }
        }
        pathSumDFS(root->left, sum, level + 1, path, res);
        pathSumDFS(root->right, sum, level + 1, path, res);
        path[level] = INT_MIN;
    }
    void savePath(vector<int> &path, int start, int end, vector<vector<int> > &res) {
        vector<int> out;
        for (int i = start; i <= end; ++i) {
            out.push_back(path[i]);
        }
        res.push_back(out);
    }
    int getDepth(TreeNode *root) {
        if (!root) return 0;
        return 1 + max(getDepth(root->left), getDepth(root->right));
    }
};
时间: 2024-10-29 19:10:26

[CareerCup] 4.9 All Paths Sum 所有路径和的相关文章

Leetcode:Path Sum 二叉树路径和

Path Sum: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return

BZOJ 1718: [Usaco2006 Jan] Redundant Paths 分离的路径( tarjan )

tarjan求边双连通分量, 然后就是一棵树了, 可以各种乱搞... ------------------------------------------------------------------------------- #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 5009; struct edge { int to; b

【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】

[062-Unique Paths(唯一路径)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to

【LeetCode-面试算法经典-Java实现】【112-Path Sum(路径和)】

[112-Path Sum(路径和)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree an

1718: [Usaco2006 Jan] Redundant Paths 分离的路径

1718: [Usaco2006 Jan] Redundant Paths 分离的路径 Time Limit: 5 Sec  Memory Limit: 64 MB链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1718 Description In order to get from one of the F (1 <= F <= 5,000) grazing fields (which are numbered 1..F) to an

LeetCode 437. Path Sum III(统计路径和等于sum的路径数量)

题意:统计路径和等于sum的路径数量. (1)节点值可正可负 (2)路径两端不一定是根结点或叶子结点 (3)路径一定是向下 分析:路径起点 (1)位于root(统计以root开头的和等于sum的路径数量) (2)位于root->left子树(递归) (3)位于root->right子树(递归) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode

[Leetcode] 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 andsum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 题意:给定一数,在树中找出所有路径和等于该数的情况.方

LeetCode 62 _ Unique Paths 全部不同路径

Description:  A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked

LeetCode 113. Path Sum II路径总和 II (C++)

题目: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 Return: [ [5,4,11