zoukankan      html  css  js  c++  java
  • 【LeetCode】113. 路径总和 II

    题目

    给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

    说明: 叶子节点是指没有子节点的节点。

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

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

    返回:

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

    本题同【剑指Offer】面试题34. 二叉树中和为某一值的路径

    思路一:回溯

    代码

    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> res;
            if (root) {
                vector<int> path;
                find(root, sum, res, path);
            }
            return res;
        }
    
        void find(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path) {
            sum -= root->val;
            path.push_back(root->val);
            if (sum == 0 && !root->left && !root->right) {
                res.push_back(path);
                return;
            }
            if (root->left) {
                find(root->left, sum, res, path);
                path.pop_back(); //回溯
            }
            if (root->right) {
                find(root->right, sum, res, path);
                path.pop_back(); //回溯
            }
        }
    };
    

    另一种写法

    class Solution {
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<vector<int>> res;
            vector<int> path;
            if (!root) {
                return res;
            }
            find(root, sum, res, path);
            return res;
        }
        void find(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path) {
            if (!root) {
                return;
            }
            path.push_back(root->val);
            if (!root->left && !root->right && sum == root->val) {
                res.push_back(path);
            }
            find(root->left, sum-root->val, res, path);
            find(root->right, sum-root->val, res, path);
            path.pop_back();
        }
    };
    
  • 相关阅读:
    PHP学习
    python获取命令行参数 启动文件
    SQLServer中char、varchar、nchar、nvarchar的区别
    VBA
    python 爬虫资料
    python乱码问题之爬虫篇
    angularjs component
    通过jQuery Ajax使用FormData对象上传文件
    directive完成UI渲染后执行JS
    交易日志
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12374952.html
Copyright © 2011-2022 走看看