您的位置:首页 > 其它

Leetcode 112. Path Sum 路径和 解题报告

2016-09-24 13:36 471 查看

1 解题思想

题目意思是给了一个二叉树,每个节点对应一个值,同时给了一个指定的树。

然后请问是否有一条从根节点开始,到叶节点的路径,其和正好等于那个值。

做法就是简单的DFS,如果到了叶节点刚好等于那个值就返回True,如果不够或者超过则返回False(搜索的时候如果还没到叶节点就超了,就回溯回去)。

2 原题

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.


3 AC解

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

/**
* 直接dfs就好了。。。就是注意下区分根节点和叶节点的定义,我当时都被坑了
*
* 叶节点是左右都没有孩子。。我一开始被坑了。。
*/
public class Solution {
public boolean dfs(TreeNode root,int sum){
if(root==null)
return false;
sum-=root.val;
if(root.left==null && root.right==null)
return sum==0;
return dfs(root.left,sum) || dfs(root.right,sum);
}
public boolean hasPathSum(TreeNode root, int sum) {
return dfs(root,sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息