zoukankan      html  css  js  c++  java
  • leetcode113.路径总和II

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

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

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

        5
       /
      4   8
      /    /
      11    13  4
     /         /
    7  2       5   1
    返回:

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

    和112题不同的是要保存每条符合条件的路径,path实现上有两种方法,一种是作为成员变量,需要自己写回退的时机,另一种是作为参数值传递,当返回上一层时path数组自动恢复上一层的值。

    方法一(path作为成员变量):

    class Solution {
        vector<int> path;
        vector<vector<int>> res;
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) 
        {
            if(!root) return res;
            
            findpath(root, sum);
            return res;
        }
    
        void findpath(TreeNode *root, int sum)
        {
            if(!root->left && !root->right && root->val == sum) {
                path.push_back(root->val);
                res.push_back(path);
                path.pop_back();
                return;
            }
            if(!root->left && !root->right) return;
            
            //非叶节点
            path.push_back(root->val);
            if(root->left) findpath(root->left, sum - root->val);
            if(root->right) findpath(root->right, sum - root->val);
            
            path.pop_back();
        }
    };

    方法二:

    class Solution {
        vector<vector<int>> res;
    public:
        vector<vector<int>> pathSum(TreeNode* root, int sum) 
        {
            if(!root) return res;
            vector<int> path;
            findpath(root, path, sum);
            return res;
        }
    
        void findpath(TreeNode *root, vector<int> path, int sum)
        {
            if(!root->left && !root->right && root->val == sum) {
                path.push_back(root->val);
                res.push_back(path);
                return;
            }
            if(!root->left && !root->right) return;
            //else {
                path.push_back(root->val);
                if(root->left) findpath(root->left, path, sum - root->val);
                if(root->right) findpath(root->right, path, sum - root->val);
            //}
            
        }
    };
  • 相关阅读:
    android 自定义日历控件
    android 常用类
    真假空格风波
    设计模式的初衷---“委托”有感
    pymysql.err.InterfaceError: (0, '')
    微信文章收藏到有道云笔记PC版只保留了标题
    SQL Server数据库字典生成SQL
    nhibernate常见错误
    NUnit
    使用ffmpeg截取视频
  • 原文地址:https://www.cnblogs.com/joker1937/p/13081816.html
Copyright © 2011-2022 走看看