【LeetCode & 剑指offer刷题】树题9:34 二叉树中和为某一值的路径(112. Path Sum)...

【LeetCode & 剑指offer刷题】树题9:34 二叉树中和为某一值的路径(112. Path Sum)

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

112. 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.
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         1
return true, as there exist a root-to-leaf path   5->4->11->2   which sum is 22.
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*
只要求返回true或false,因此不需要记录路径
*/
class Solution
{
public :
    bool hasPathSum ( TreeNode * root , int sum )
    {
        if ( root == nullptr ) return false ;
        if ( root -> left == nullptr && root -> right == nullptr ) //叶子结点
            return sum == root -> val ;
       
        int newsum = sum - root -> val ;
        return hasPathSum ( root -> left , newsum ) || hasPathSum ( root -> right , newsum );
    }
};
 
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.
Note:  A leaf is a node with no children.
Example:
Given the below binary tree and   sum = 22 ,

 

Return:
[
[5,4,11,2],
[5,8,4,5]
]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*
求所有和等于某数的路径
*/
#include <numeric> //算容器类元素和可用accumulate函数
class Solution
{
public :
    vector < vector < int >> pathSum ( TreeNode * root , int sum )
    {
        vector < vector < int >> result ;
        vector < int > path ;
        path_sum ( root , path , result , sum );
        return result ;
    }
private :
    void path_sum ( TreeNode * root , vector < int >& path , vector < vector < int >>& result , int gap )
    {
        if ( root == nullptr ) 
            return ; //递归出口
        else   
            path . push_back ( root -> val ); // 存储结点元素到path
       
        if ( root -> left == nullptr && root -> right == nullptr ) //叶子结点时push path到结果向量中
        {
            if ( gap == root -> val ) result . push_back ( path ); //如果该path和为sum则push到结果向量中(这里用sum累减路径上的元素,得到gap与路径上最后一个元素比较,节省时间,如果得到path再accumulate,则会造成不同路径间的重复计算)
           // return; //递归出口,到叶结点后退出,(不能写这句,还需运行到结尾进行pop)
        }
       
        path_sum ( root -> left , path , result , gap - root -> val ); //沿深度方向遍历
        path_sum ( root -> right , path , result , gap - root -> val );
        path . pop_back (); // 删除最后一个元素 ,腾出空间(本函数中只push了一次,故只需pop一次)
       
       
    }
};
 

 

posted @ 2019-01-05 19:44 wikiwen 阅读( ...) 评论( ...) 编辑 收藏
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
给定一个整数数组 nums 和一个目标值 target,要求在数组找出两个数的和等于目标值,并返回这两个数的索引。 思路1:暴力法 最简单的思路是使用两层循环遍历数组的所有组合,判断两个数的和是否等于目标值。如果等于目标值,则返回这两个数的索引。 此方法的时间复杂度为O(n^2),空间复杂度为O(1)。 思路2:哈希表 为了优化时间复杂度,可以使用哈希表来存储数组的元素和对应的索引。遍历数组,对于每个元素nums[i],我们可以通过计算target - nums[i]的值,查找哈希表是否存在这个差值。 如果存在,则说明找到了两个数的和等于目标值,返回它们的索引。如果不存在,将当前元素nums[i]和它的索引存入哈希表。 此方法的时间复杂度为O(n),空间复杂度为O(n)。 思路3:双针 如果数组已经排序,可以使用双针的方法来求解。假设数组从小到大排序,定义左针left向数组的第一个元素,右针right向数组的最后一个元素。 如果当前两个向的数的和等于目标值,则返回它们的索引。如果和小于目标值,则将左针右移一位,使得和增大;如果和大于目标值,则将右针左移一位,使得和减小。 继续移动针,直到找到两个数的和等于目标值或者左针超过了右针。 此方法的时间复杂度为O(nlogn),空间复杂度为O(1)。 以上三种方法都可以解决问题,选择合适的方法取决于具体的应用场景和要求。如果数组规模较小并且不需要考虑额外的空间使用,则暴力法是最简单的方法。如果数组较大或者需要优化时间复杂度,则哈希表或双针方法更合适。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值