标签:
简单递归,但代码简洁性有待提高
我的代码
/** * 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); } };
标签:
原文地址:http://www.cnblogs.com/llei1573/p/4323471.html