Path Sum

https://leetcode.com/problems/path-sum/

使用递归的方法

/**
 * 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;
        }
        bool left_res=false;
        bool right_res=false;
        
        if(root->left==NULL&&root->right==NULL)
        {
            if(sum==root->val)
                return true;
        }
        
       
        if(root->left!=NULL)
        {
            left_res=hasPathSum(root->left,sum-(root->val));
        }
        if(left_res==false&&root->right!=NULL)
        {
            right_res=hasPathSum(root->right,sum-(root->val));
        }
        if(left_res==true||right_res==true)
            return true;
        else
            return false;
    }
};

  

原文地址:https://www.cnblogs.com/aguai1992/p/5029155.html