leetCode 112.Path Sum (路径和) 解题思路和方法
来源:互联网 发布:华迈网络摄像机 编辑:程序博客网 时间:2024/06/05 11:10
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
思路:求解二叉树的路径和是否满足sum。需要考虑的一点就是有负数,而且如果为0的时候也不能结束,以为也有可能下面的和为0.
题目不难,只是有一些小的点需要注意。具体代码如下:
/** * 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) { /** * 判断根节点是否为空和值是否大于sum,是则false * 然后判断val和sum是否相等,如果相等且root没有子树。true * 不相等则递归判断左右子树是否与sum-val相等 */ if(root == null){//注意,此处不能判断val与sum大小,因为存在负数 return false; } if(root.val == sum){ //注意:因为存在负数,所以左右子树不为空也不能直接返回flase //有可能左右子树的和值为0 if(root.left == null && root.right == null) return true; } //小于 return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val); }}
0 0
- leetCode 112.Path Sum (路径和) 解题思路和方法
- leetcode 113. Path Sum II (路径和) 解题思路和方法
- Leetcode 112. Path Sum 路径和 解题报告
- leetCode 71.Simplify Path(化简路径) 解题思路和方法
- LeetCode 112. Path Sum(路径和)
- leetCode 64.Minimum Path Sum (最短路) 解题思路和方法
- (解题思路转换)LeetCode#112. Path Sum
- Leetcode 64. Minimum Path Sum 最小路径和 解题报告
- Leetcode 113. Path Sum II 路径和2 解题报告
- Leetcode 437. Path Sum III 路径和3 解题报告
- leetCode 18.4Sum (4数字和) 解题思路和方法
- LeetCode | Path Sum(路径和)
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- leetCode 1. Two Sum 解题思路和方法
- leetCode 39.Combination Sum(组合总和) 解题思路和方法
- leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)
- OC习题 -- 切分字符串 处理色值和名称 (知识点: 字典,枚举,数组,字符串)
- HTTP Live Streaming协议标准各个草案修改Track
- android应用中去掉标题栏的方法
- 数组,字符串复习+排序
- 代码整洁之道--单元测试
- leetCode 112.Path Sum (路径和) 解题思路和方法
- HLS 加密细节
- 关于birt报表db数据源内存溢出的处理方法
- POJ - 1698 Alice's Chance (二分图多重匹配)
- 黑马程序员_Java基础:可变参数(Varagrs)的使用注意事项
- 解决: ERROR JDBCExceptionReporter:78 - Could not retrieve transation read-only status server
- 探索MySQL权限表
- MongoDB——分片
- hdu 1274 展开字符串