112. Path Sum

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.

Notice:

  • Special case for empty tree and sum=0
  • Four case none leaf node with only one child
/**
 * 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 fun(TreeNode* root, int sum){
        if(NULL == root){
            if(sum == 0) return true;
            else return false;
        }else{
            if(NULL == root->left && NULL == root->right){
                if(sum == root->val) return true;
                else return false;
            }else if(NULL == root->left && NULL != root->right){
                return fun(root->right, sum - root->val);
            }else if(NULL != root->left && NULL == root->right){
                return fun(root->left, sum - root->val);
            }else{
                return fun(root->left, sum - root->val) || fun(root->right, sum - root->val);
            }
        }
    }
    bool hasPathSum(TreeNode* root, int sum) {
        if(NULL == root) return false;
        else return fun(root, sum);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 昨天因为看SJ的周偶没有写,现在回到了学校的宿舍,和小组成员们吃了饭回来,恭喜明哥获得了湿喷组的第一个国奖。作为研...
    忆江南1991阅读 208评论 0 0
  • 让我们重温书中的那些经典吧~~~~ 1、那些人的光环来自他们的职位,而非自身的本事。P3 2、每天做两件自己讨厌的...
    青梅149阅读 45,257评论 4 6
  • 春雨,是我们的狂欢,喜欢春雨淋在身上的感觉,那毛毛细雨,洋溢着春的气息,等这一天,好久了。翠绿色的植物在雨中跳舞,...
    jeepl阅读 395评论 0 0
  • 整日淹没在城市的人山人海之中,紧张快节奏的城市化生活使我感到身心疲惫。喧嚣的街道,热闹的酒...
    吃蔬菜的狮子阅读 321评论 0 0