[LeetCode] Path Sum

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

[LeetCode] Path SumGiven 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 andsum = 22,

5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1

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

这道题挺简单的,直接用recursive做就可以了。因为反正每一个node检查的方式都一样。

只要目前的sum减去正在检查的node的value之后等于0,就可以return true。

所以程序还是很简单的。

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean haspathSum(TreeNode root, int sum) { if(root==null){ return false; } sum=sum-root.val; if(root.left==null&&root.right==null){ if(sum==0){ return true; } return false; } return hasPathSum(root.left,sum)||hasPathSum(root.right,sum); }}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航