[题解]剑指 Offer 34. 二叉树中和为某一值的路径(C++)

题目

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

示例:
给定如下二叉树,以及目标和 target = 22,

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

返回:

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

提示:

  1. 节点总数 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

DFS题,用一个数组path存当前遍历到的路径,当抵达叶节点且和为target的时候将path存入结果ans数组中。递归时可以在经过一个节点时用target的值减去该节点的值,这样最后只需要判断target是否为0即可,用传值的方法传target。记得使用标记清除。
时间复杂度O(n2),空间复杂度O(n)。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    vector<vector<int>> pathSum(TreeNode* root, int target) {
        if(!root) return ans;
        path.push_back(root->val);

        dfs(root, ans, path, target - root->val);
        return ans;
    }

    void dfs(TreeNode *cur, vector<vector<int>>& ans, vector<int>& path, int target)
    {
        if(target == 0 && !cur->left && !cur->right)
        {
            ans.push_back(path);
            return;
        }
        if(cur->left)
        {
            path.push_back(cur->left->val);
            dfs(cur->left, ans, path, target - cur->left->val);
            path.pop_back();
        }
        if(cur->right)
        {
            path.push_back(cur->right->val);
            dfs(cur->right, ans, path, target - cur->right->val);
            path.pop_back();
        }
    }
};
posted @   浮生的刹那  阅读(27)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
  1. 1 Night City r e l,Artemis Delta
  2. 2 Gold Steps(人生何处不青山) Neck Deep
  3. 3 Devil Trigger Ali Edwards
  4. 4 Hopeless Case Roam
  5. 5 On My Own Blitz Kids
  6. 6 I Really Want to Stay At Your House Rosa Walton & Hallie Coggins
  7. 7 Major Crimes Health & Window Weather
Night City - r e l,Artemis Delta
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.
点击右上角即可分享
微信分享提示