Path Sum II :from LeetCode

题目大意是:将二叉树中根到叶子的所有路径中节点值的和为给的的数字sum的路径返回,当然路径是以保存节点值而非指针的形式。

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]
]
解题思想可以沿用之前的path sum,只是这时我们需要存储从根到当前节点的路径上的所有点,只要一发现有符合条件的路径,保存就ok。

而这些点保存的形式很容易想到栈,我最开始单纯地想用VECTOR实现这个栈,当然结果是超时,代码如下,大家看看是不是有其他的问题:

class Solution {
public:
    vector<vector<int>>result;
    vector<int> tmp;
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        int num;
        if(!root)
            return result;
        tmp.push_back(root->val);
        if(!root->right && !root->left && root->val==sum)
        {
            result.push_back(tmp);
            tmp.pop_back();
            return result;
        };
        if(!root->right && !root->left)
        {
            tmp.pop_back();
            return result;
        }
        pathSum(root->left,sum-root->val);
        pathSum(root->right,sum-root->val);
        tmp.pop_back();
        return result;
    }
};

以为是这种方法不行,但在别人提醒下认为是数据结构不行。所以改用数组来实现栈,结果AC,代码如下

class Solution {
public:
    vector<vector<int>>result;
    vector<int> tmp;
    int arry[10000];
    int index;
    
    void dfs(TreeNode *root,int sum)
    {
        if(!root)
            return;
        arry[index++]=root->val;
        if(!root->right && !root->left && root->val==sum)
        {
            tmp.clear();
            for(int i=0;i<index;i++)
            {
                tmp.push_back(arry[i]);
            }
            result.push_back(tmp);
            index--;
            return;
        };
        if(!root->right && !root->left)
        {
            index--;
            return ;
        }
        dfs(root->left,sum-root->val);
        dfs(root->right,sum-root->val);
        index--;
        return ;
    }
    
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        if(!root)
            return result;
        index=0;
        dfs(root,sum);
        return result;
    }
};

当然定义一个数组成员总是会让人觉得不快,因为面试官总会拿数据冗余或者空间复杂度来反问你。但在时空问题上总得有些取舍,但空间更优的方法总有,大家想想。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值