`
king_tt
  • 浏览: 2112039 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

【leetcode】Path Sum II

 
阅读更多

Question:

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 andsum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

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

Anwser 1:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){
        if(root == NULL){
            return;
        }
        
        tmp.push_back(root->val);
        if(sum == root->val && root->left == NULL && root->right == NULL){
            ret.push_back(tmp);
        }
        
        calPath(root->left, sum - root->val, tmp, ret);
        calPath(root->right, sum - root->val, tmp, ret);
        
        tmp.pop_back();
    }

    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector< vector<int> > ret;
        
        if(root == NULL) {
            return ret;
        }
        
        vector<int> tmp;
        calPath(root, sum, tmp, ret);
        return ret;
    }
};


Anwser 2:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void calPath(TreeNode *root, int sum, vector<int> tmp, vector< vector<int> > &ret){
        if(root == NULL){
            return;
        }
        
        tmp.push_back(root->val);
        if(sum == root->val && root->left == NULL && root->right == NULL){
            ret.push_back(tmp);
            tmp.pop_back();     // pop tmp vector
            return;
        }
        
        calPath(root->left, sum - root->val, tmp, ret);
        calPath(root->right, sum - root->val, tmp, ret);
        
        tmp.pop_back();
    }

    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector< vector<int> > ret;
        
        if(root == NULL) {
            return ret;
        }
        
        vector<int> tmp;
        calPath(root, sum, tmp, ret);
        return ret;
    }
};


分享到:
评论

相关推荐

    LeetCode -- Path Sum III分析及实现方法

    主要介绍了LeetCode -- Path Sum III分析及实现方法的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下

    LeetCode — Path Sum III分析及实现方法

    LeetCode — Path Sum III分析及实现方法 题目描述: You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need...

    【leetcode】【medium】113. Path Sum II

    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. Note: A leaf is a node with no children. Example: Given the below binary tree...

    LeetCode最全代码

    371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | ...

    javalruleetcode-LeetCode::lollipop:个人LeetCode习题解答仓库-多语言

    java lru leetcode :ice_cream: LeetCode Kindem 的个人 LeetCode 题解仓库,欢迎交流学习。 下面的目录中 $number 题号代表经典 LeetCode 题目,$number.$number ...LeetCode ...Sum ...Sum ...Sum ...Path Sum 73

    多线程leetcode-leetcode-java:leetcode上的题解,基于java语言

    多线程 leetcode 前言 每天刷点leetcode,基于java语言...Path Sum II Copy List with Random Pointer Building H2O Fizz Buzz Multithreaded hard Merge k Sorted Lists Reverse Nodes in k-Group Trapping Rain Water

    leetcode分类-LeetCode:力码

    Path Sum Unique Paths Unique Paths II Longest Palindromic Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal Rectangle ###Recursion N-Queens N-...

    TWDH#Leetcode-From-Zero#07.路径总和1

    //将每一种可能性都放入set中,并依次与sum对比public int pathSum(TreeNode root, int mySum){//1.递归出口/

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    leetcode 【演示记录】 报告 展示 2017/03/06 1.二和,167.二和二 2107/03/06 15.3 总和,16.3 总和最近,18.4 总和,11.最多水的容器 2017/03/09 62.Unique Paths, 63.Unique Paths II, 64.Minimum Path Sum 2017/...

    leetcode叫数-Leetcode_JS:leetcode编程题,javascript版本

    leetcode叫数 Leetcode_JS leetcode编程题,javascript版本 ##NO.35 Search Insert Position 这道题非常简单,数组是有序数组,只需要遍历一遍...Sum 这道题是关于二叉树的题,递归思路,也就是DFS的思路。 这里递归

    leetcode:C,C ++,Java和Python的LeetCode解决方案

    $ cd /path/to/leetcode/c/ # /path/to/leetcode/cpp/ $ mkdir build $ cd build $ cmake .. $ cd .. CMake将自动生成buildsystem文件并下载 。 注意:添加新的单元测试后,请务必重新加载CMake。 要构建,请使用--...

    戳气球leetcode-Leetcode_notes:C++中的leetcode解决方案

    leetcode 做题笔记 按照知识点分类 链表 链表反转 分治: 回溯/递归 全排列问题,用visited变量; 组合问题,用start变量。 其它 动态规划 区间型 [从左上角到右下角] [子序列/子串:公共长度问题,都是DP,只有一个...

    cpp-算法精粹

    Path Sum II Binary Tree Maximum Path Sum Populating Next Right Pointers in Each Node Sum Root to Leaf Numbers LCA of Binary Tree 线段树 Range Sum Query - Mutable 排序 插入排序 Insertion Sort List 归并...

    lrucacheleetcode-leetcode:leetcode

    Path to Get All Keys 深度优先搜索 996. Number of Squareful Arrays 拓扑排序 269. Alien Dictionary 单调栈 42. Trapping Rain Water 85. Maximal Rectangle Monotonic stack for 2d array 239. Sliding Window ...

    刷leetcode不用stl-3-leetcode-everyday:每天3个leetcode!!!

    1、two-sum 能同时获取元素和index的方法是使用enumerate() 思路:从第一个元素开始,遍历,求每个位置上的差值保存到dict中,如果在接下来的元素在dict中出现,返回下标。。。真牛逼! 7、Reverse integer 字符串...

    四平方和定理leetcode-leetcode-practice:个人LeetCode练习代码

    四平方和定理 leetcode Leetcode practice Table of content Tree 92.reverse-linked-list-ii ...112.path-sum (路径总和) 116.populating-next-right-pointers-in-each-node (填充每个节点的下一个右侧节点

    algorithm:通过hackerrank,codeforce,leetcode等练习练习编码。

    算法命令行界面设置样板来解决问题。 要使用CLI,请执行以下步骤cd bin/npm link用法al new [name] [arguments] 示例1... 示例2:带有参数al new path - sum node sum 输出var pathSum = function ( node , sum ) { } ;

    Anfany#LeetCode_Python3_Solution#64 最小路径和1

    二、Python3程序64_Minimum_Path_Sum 最小路径和# 利用动态规划的方法# 要到达索引为[r,l]的网格# 一是从[r,l-1]的网格向右

    leetcode338-algorithm-training:leetcodecjava

    第 338 章力码解决方案 问题编号 标题 困难 C Java Ruby 338 中等的 [✓](/src/338 计数位/solution.c) 104 简单的 [✓](/src/104 ...II/solution.c) ...Path Sum II/solution.java) 258 简单的 [✓](/

    leetcode2-leetup:解决Leetcode问题的命令行工具。加油!!

    PATH 以从命令提示符访问。 快速开始: 使用 Github 登录: leetup user -g 使用cookie登录: leetup user -c leetup pick -l python 1 : leetup pick -l python 1 测试一个问题: leetup test two-sum.py -t "[1,2...

Global site tag (gtag.js) - Google Analytics