leetcode: Path Sum

来源:互联网 发布:帝国时代2网络对战 编辑:程序博客网 时间:2024/06/10 00:57

递归,判断如果是叶子且路径和等于目标就返回true

/** * Definition for binary tree * 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;        return core( root, sum, 0);    }    bool core( TreeNode *root, int sum, int cur){        if( root->left == NULL && root->right == NULL){            if( root->val + cur == sum)                return true;            else                return false;        }        else if( root->left == NULL){            return core( root->right, sum, cur+root->val);        }        else if( root->right == NULL){            return core( root->left, sum, cur+root->val);        }        else{            return core( root->left, sum, cur+root->val) || core( root->right, sum, cur+root->val);        }    }};


0 0
原创粉丝点击