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;
    }
};

  

posted @ 2015-12-08 15:02  阿怪123  阅读(104)  评论(0编辑  收藏  举报