码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 112

时间:2019-02-02 12:56:45      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:def   nod   solution   etc   ||   als   null   return   str   

/**
 * 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 == NULL) return false;
        int flag = 0;
        DFS(root,sum,flag);
        if(flag) return true;
        else return false;
    }
    void DFS(TreeNode* root, int sum,int& flag){
        if((root->left == NULL)&&(root->right == NULL)){
            if(root->val == sum)
                flag = 1;
        }
        else if((root->left != NULL)&&(root->right == NULL)){
            root->left->val += root->val;
            DFS(root->left,sum,flag);
        }
        else if((root->left == NULL)&&(root->right != NULL)){
            root->right->val += root->val;
            DFS(root->right,sum,flag);
        }
        else if((root->left != NULL)&&(root->right != NULL)){
            root->left->val += root->val;
            DFS(root->left,sum,flag);
            root->right->val += root->val;
            DFS(root->right,sum,flag);
        }
        return;
    }
};

__

简便写法:

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(root->left == NULL && root->right == NULL) return root->val == sum;
        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); //sum - root->val很灵性
    }
};

 

Leetcode 112

标签:def   nod   solution   etc   ||   als   null   return   str   

原文地址:https://www.cnblogs.com/cunyusup/p/10348186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!