zoukankan      html  css  js  c++  java
  • LeetCode 113. 路径总和 II 树的遍历

    地址 https://leetcode-cn.com/problems/path-sum-ii/

    给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
    
    说明: 叶子节点是指没有子节点的节点。
    
    示例:
    给定如下二叉树,以及目标和 sum = 225
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    返回:
    
    [
       [5,4,11,2],
       [5,8,4,5]
    ]
    
     

    算法1
    进行树的遍历 额外的记录路径和计算和

    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>> ans;
        vector<int> v;
        void dfs(TreeNode* root, int sum){
            if(root == NULL) return;
            v.push_back(root->val);
            sum -= root->val;
            if(sum ==0 && root->left == NULL && root->right == NULL){ans.push_back(v);v.pop_back(); return;}
    
            dfs(root->left,sum);
            dfs(root->right,sum); 
            v.pop_back();
        }
    
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            dfs(root,sum);    
            return ans;
        }
    };
    
     
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    查看SQL Server版本号(2005 & 2008)
    Installing an App for Testing
    Viewstate 的用法
    How to Open the Pdf file?
    工具类:Log
    SPSiteDataQuery and SPQuery
    SPSite, SPWeb Dispose and Class Design Partter
    Add Properties or Delete List Folder Content Type
    SharePoint UserControl
    Click Once 布署
  • 原文地址:https://www.cnblogs.com/itdef/p/13735528.html
Copyright © 2011-2022 走看看