LeetCode题解——Path Sum

原创 2015年11月17日 21:55:48

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.

it's easy to use recursion to solve the problem

/**
 * 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:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(!root->left && !root->right) return sum==root->val;
        bool flage = false;
        if(root->left) flage = hasPathSum(root->left,sum-root->val);
        if(flage) return true;
        else{
            if(root->right) return hasPathSum(root->right,sum-root->val);
            else return false;
        }
    } 
};


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

相关文章推荐

LeetCode题解——Path Sum II

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

LeetCode题解:Path Sum

题目链接:Path Sum题目描述: Given a binary tree and a sum, determine if the tree has a root-to-leaf path su...
  • yums467
  • yums467
  • 2015年07月16日 10:31
  • 297

leetcode_题解_path sum 2

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

LeetCode Algorithms 113. Path Sum II 题解

题目 Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the gi...

LeetCode112.Path Sum题解

1. 题目描述Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that add...
  • lby0910
  • lby0910
  • 2017年03月13日 17:18
  • 117

LeetCode题解:Path Sum I and II

Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that ...
  • MagiSu
  • MagiSu
  • 2013年11月07日 14:17
  • 682

LeetCode刷题(C++)——Minimum Path Sum(Medium)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode112——Path Sum

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

LeetCode——Binary Tree Maximum Path Sum

链接:http://leetcode.com/onlinejudge#question_124 原题: Given a binary tree, find the maximum path s...

LeetCode题解——Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a numb...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode题解——Path Sum
举报原因:
原因补充:

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