Recusion solution is clear


  • 1
    R
    class Solution {
    public:
    	bool hasPathSum(TreeNode *root, int sum) {
    		if (NULL == root)
    		{
    			return false;
    		}
    		if (NULL == root->left && NULL == root->right)
    		{
    			/* is leaf node */
    			return (root->val == sum);
    		}
    		if (hasPathSum(root->left, sum - root->val))
    		{
    			return true;
    		}
    		return hasPathSum(root->right, sum - root->val);
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.