Path Sum

简单递归,但代码简洁性有待提高

我的代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
  * };
 */
bool hasPathSum(struct TreeNode *root, int sum) {
    if(root == NULL) return false;
    if(root->left == NULL && root->right == NULL){
        if(sum == root->val) return true;
        return false;
    }
    bool ok = false;
    ok = hasPathSum(root->left,sum-root->val);
    if(ok == true) return true;
    ok = hasPathSum(root->right,sum-root->val);
    return ok;
}

别人的比较简洁的代码

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

 

posted @ 2015-03-09 14:13  SprayT  阅读(86)  评论(0编辑  收藏  举报