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

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);
    }
时间: 2024-07-31 10:45:44

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

关于Android4.4的图片路径获取,如果回来的Uri的格式有两种

关于Android4.4的图片路径获取,如果回来的Uri的格式有两种1.content://com.android.providers.media.documents/document/image:39512.content://media/external/images/media/3951 解决办法:    1).        //>=4.4    时        if(DocumentsContract.isDocumentUri(context, contentUri)){     

124. Binary Tree Maximum Path Sum *HARD* -- 二叉树中节点和最大的路径的节点和

Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For exampl

Shell中调用/引用/包含另外的脚本文件的两种方法

脚本 first (测试示例1) #vi  first.sh 1 #!/bin/bash 2 echo 'your are in first file' 问)在当前脚本文件中调用另外一个脚本文件? 方法一: 使用 source 脚本 second (测试示例2)# vi second.sh 1 #!/bin/bash 2 echo 'your are in second file' 3 source first.sh 注意事项:分别建立# vi first.sh 和 second.sh 测试:#

第四周 Leetcode 124. Binary Tree Maximum Path Sum (HARD)

124. Binary Tree Maximum Path Sum 题意:给定一个二叉树,每个节点有一个权值,寻找任意一个路径,使得权值和最大,只需返回权值和. 思路:对于每一个节点 首先考虑以这个节点为结尾(包含它或者不包含)的最大值,有两种情况,分别来自左儿子和右儿子设为Vnow. 然后考虑经过这个节点的情况来更新最终答案.更新答案后返回Vnow供父节点继续更新. 代码很简单. 有一个类似的很有趣的题目,给定一个二叉树,选择一条路径,使得权值最大的和最小的相差最大.参考POJ3728 cla

LeetCode124 Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. (Hard) For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does n

Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 求二叉树从根到叶子结点,结点和等于sum的所有路径.

两种解决头文件被重复包含方法的联系与区别

在制作C/C++项目的过程中,应该会遇到关于头文件被重复包含的问题,几乎每一个C/C++程序员都应该知道如何来解决这一问题.通常来说,我们通常可以用两种方式来解决这一问题. 第一种 ---- 利用以下形式: #ifndef  __XX_H__                                                                              #ifndef   XX_H #define __XX_H__                    

Project Euler 83:Path sum: four ways 路径和:4个方向

Path sum: four ways NOTE: This problem is a significantly more challenging version of Problem 81. In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red an

Project Euler 80:Path sum: two ways 路径和:两个方向

Path sum: two ways In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.           131 673 234 103 18 201 96 342 965 150 630 803 74