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

Path Sum 路径和(注:同时包含得到各个路径的模板:两种不同表达形式的代码)

时间:2016-05-07 09:11:08      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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.

For example:
Given the below binary tree and sum = 22,
              5
             /             4   8
           /   /           11  13  4
         /  \              7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

题目大意:判断是否存在一条路径,且其上的和与给定的sum相等。


1.我的解法(递归)

/**
 * 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 pathsum(TreeNode* root, int all, int sum){
        if(root->left== NULL && root->right == NULL){
            if(all+root->val == sum)
            return true;
            else
            return false;
        }
        if(root->left== NULL || root->right == NULL){//这里需要处理只有一个子节点的情况,不能把有空的那条算为路径
            TreeNode* t = root->left!=NULL?root->left:root->right;
            return pathsum(t,all+root->val,sum);
        }else{
            return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum);
        }
    }

    bool hasPathSum(TreeNode* root, int sum) {
        if(!root)
        return false;
        return pathsum(root,0,sum);
    }
};

对上面做改进。这里主要就是针对某个节点只有一个左/右节点该怎么处理。

上面做法是,如果碰到只有一个子节点,则将那个子节点传下去;

下面的做法是,如果碰到空了(只有一个子节点,则另一个子节点就是为空,),那么这个分叉不属于一条路径,则直接置false。

因为只有到叶子节点(左右都为空),才算一条路径。

/**
 * 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 pathsum(TreeNode* root, int all, int sum){
        if(root==NULL)
        return false;
        if(root->left== NULL && root->right == NULL){
            if(all+root->val == sum)
            return true;
            else
            return false;
        }
        return pathsum(root->left,all+root->val,sum)||pathsum(root->right,all+root->val,sum);
        
    }

    bool hasPathSum(TreeNode* root, int sum) {
        if(!root)
        return false;
        return pathsum(root,0,sum);
    }
};



2.别人的解法(递归)

bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL) return false;
        if (root->val == sum && root->left ==  NULL && root->right == NULL) return true;
        return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
    }


Path Sum 路径和(注:同时包含得到各个路径的模板:两种不同表达形式的代码)

标签:

原文地址:http://blog.csdn.net/u010005161/article/details/51330237

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