zoukankan      html  css  js  c++  java
  • 113.Path Sum II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

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

    return

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

    思路:DFS. 如果root为空,直接返回空数组,否则调用help函数。help函数将传入的root节点值压入cur数组,更新当前数组cur的和值now,如果root为叶子节点,且cur数组和为target,则将cur数组压入ret。如果左子结点不为空,递归调用 help(root->left,cur,now,target),右子结点不为空,递归调用 help(root->right,cur,now,target)。请注意,cur数组不能传入引用参数,应该传入形参。每个递归函数在运行过程中对cur数组的操作都是各自为政,互不干涉的。

     
    /**
     * 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>> ret;
        void help(TreeNode *root,vector<int> cur,int now,int target){
            now+=root->val;
            cur.push_back(root->val);
            if(!root->left&&!root->right){
                if(now==target)
                    ret.push_back(cur);
                return;
            }
            if(root->left)
                help(root->left,cur,now,target);
            if(root->right)
                help(root->right,cur,now,target);
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            if(!root)
                return ret;
            vector<int> temp;
            help(root,temp,0,sum);
            return ret;
        }
    };

     



  • 相关阅读:
    [色彩校正] Gamma Correction
    需要齐次坐标的原因之二 所有的变换运算(平移、旋转、缩放)都可以用矩阵乘法来搞定
    需要齐次坐标的原因之一
    数据库连接类
    简单的数组排序
    OfficePage封装代码
    新闻管理数据模板
    最新page页码生成控件代码
    新闻管理cs页面
    快速收录新域名网站
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5043195.html
Copyright © 2011-2022 走看看