Path Sum
来源:互联网 发布:ubuntu suspend 编辑:程序博客网 时间:2024/06/06 08:55
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.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean hasPathSum(TreeNode root, int sum) { return pathSum(root,sum,0); } public boolean pathSum(TreeNode node,int sum,int path){ if(node==null) return false; if((node.val+path)==sum && node.left==null && node.right==null) return true; else return pathSum(node.left,sum,node.val+path)||pathSum(node.right,sum,node.val+path); }}思路:递归,注意,题目要求,结尾的必须是叶子节点。
0 0
- Path Sum && Path Sum ||
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- 习题3-10 盒子 UVa1587
- Django:错误集合
- Andrew ng清华报告
- 2014-7 Andrew Ng 自动化所报告
- 要想进步必须得不停得学习
- Path Sum
- 重定向的一些小记录,个人粗略的不成熟的理解
- Topic Model(主题模型)交流
- 一个十分有趣的字符串算法, 转载留个记号
- CentOS创建本地yum源
- JAVA 复习(Think In Java, 4th) -- Inner Classes - Part1
- qt 中如何向QTableWidget里大量添加数据?
- Hdu2037 - 今年暑假不AC - 贪心算法
- http协议常用请求头与响应头