码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num112_Path Sum

时间:2015-03-08 17:12:04      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dfs   

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

/**
 * Definition for binary tree
 * 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;
        int y;
        y=root->val;
        if ((root->left==NULL) and (root->right==NULL)){
            if (y==sum)
                return true;
            else 
                return false;
            }
        else{
            int z;
            z=sum-y;
            bool check,check1,check2;
            check1=hasPathSum(root->left,z);
            check2=hasPathSum(root->right,z);
            check= (check1 or check2);
            return check;
        }
    }
};


leetcode_num112_Path Sum

标签:leetcode   dfs   

原文地址:http://blog.csdn.net/eliza1130/article/details/44134191

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!