剑指Offer: 二叉树中和为某一值的路径

剑指Offer: 二叉树中和为某一值的路径

题目描述

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。

从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。。

给出二叉树如下所示,并给出num=225
     / \
    4   6
   /   / \
  12  13  6
 /  \    / \
9    1  5   1

输出:[[5,4,12,1],[5,6,6,5]]

算法 递归+回溯

  • 遍历一遍树的节点,沿节点向下依次递增,回溯的时候,恢复上一次的状态
时空分析

时间复杂度: 树的节点遍历一遍,时间复杂度 O(n)

C++ 代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> res;//存放结果数组的数组
    vector<int> path;       //路径数组
    int expect;			    //期待的和
    int csum;               //当前和
    vector<vector<int> > findPath(TreeNode* root,int expectNumber) {
        if (!root)
            return res;
        expect = expectNumber;
        csum = 0;
        dfs(root);

        return res;
    }

    void dfs(TreeNode* root)
    {
        if (!root)
            return;

        csum += root->val;
        path.push_back(root->val);
        if (!root->left && !root->right && csum == expect)
            res.push_back(path);

        dfs(root->left);
        dfs(root->right);
		//回溯前恢复状态
        csum -= root->val;
        path.pop_back();
    }
};

使用减法可以省略存储当前和和目前和的成员变量,代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    vector<vector<int> > findPath(TreeNode* root,int expectNumber) {

        dfs(root, expectNumber);
        return res;
    }

    void dfs(TreeNode* root, int sum)
    {
        if (!root)
            return;

        sum -= root->val;
        path.push_back(root->val);
        if (!root->left && !root->right && !sum)
            res.push_back(path);

        dfs(root->left, sum);
        dfs(root->right, sum);

        sum += root->val;
        path.pop_back();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Erice_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值