Path Sum

原创 2015年11月20日 16:27:51
  1. 问题

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,
                  5
                 / \
                4   8
               /   / \
              11  13  4
             /  \      \
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

  2. 解答
    bool hasPathSum(struct TreeNode* root, int sum) 
    {
        if(root==NULL) return false;
        if(root->left==NULL && root->right==NULL && root->val==sum)
            return true;
        return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】

【064-Minimum Path Sum(最小路径和)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a m x n grid filled with no...

算法课第十周作业 | Minimum Path Sum

写在前面: 选取题目64,采用动态规划算法解决问题。 题意解读:给定一个包含m*n个非负整数的表格,找到一条从左上角到右下角的路径,使得经过该路径上的数字之和和最小。   解题思路...
  • zsrose
  • zsrose
  • 2017年04月30日 01:49
  • 64

LeetCode: Binary Tree Maximum Path Sum [124]

【题目】 Given a binary tree, find the maximum path sum. The path may start and end at any node in the...

LeetCode:Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi...

112. Path Sum(y)

112. Path Sum问题描述: 找到一条从根节点到叶子节点的路径,其上所有节点的值之和等于给定的sum。算法思路: 基本上为二叉树的深度遍历,针对sum值可以根据层级逐次减去一部分值。A 是...

LeetCode 之 Path Sum II

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

LeetCode 113. Path Sum II(路径和)

原题网址:https://leetcode.com/problems/path-sum-ii/ Given a binary tree and a sum, find all root-to-l...
  • jmspan
  • jmspan
  • 2016年05月24日 00:19
  • 326

LeetCode -- Path Sum III

LeetCode -- Path Sum III

#94 Binary Tree Maximum Path Sum

题目描述: Given a binary tree, find the maximum path sum. The path may start and end at any node...

LeetCode(124) Binary Tree Maximum Path Sum

题目 Given a binary tree, find the maximum path sum. For this problem, a path is defined as any seq...
  • fly_yr
  • fly_yr
  • 2015年12月27日 16:20
  • 1782
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Path Sum
举报原因:
原因补充:

(最多只允许输入30个字)