leetcode112. Path Sum
来源:互联网 发布:看股票用什么软件 知乎 编辑:程序博客网 时间:2024/06/07 03:32
112. 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 1return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
解法一
找到叶子结点,判断累加和是否等于target。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { int target; boolean ret; public boolean hasPathSum(TreeNode root, int sum) { target = sum; if (root == null) { return false; } helper(root, root.val); return ret; } public void helper(TreeNode root, int sum) { if (root.left == null && root.right == null) { if (sum == target) { ret = true; return; } } if (root.left != null) helper(root.left, sum + root.left.val); if (root.right != null) helper(root.right, sum + root.right.val); }}
解法二
dfs,每次减去该结点的值,直到叶子结点,判断是否值为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) { if (root == null) { return false; } if (root.left == null && root.right == null && sum - root.val == 0) { return true; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); }}
阅读全文
0 0
- leetcode112 Path Sum
- leetcode112---Path Sum
- LeetCode112—Path Sum
- leetcode112. Path Sum
- Leetcode112. Path Sum
- LeetCode112. Path Sum
- LeetCode112. Path Sum
- leetcode112~Path Sum
- LeetCode112.Path Sum题解
- LeetCode112 Path Sum
- leetcode112. Path Sum
- leetcode112 path sum
- LeetCode112. Path Sum
- LeetCode112——Path Sum
- LeetCode112. Path Sum java solution
- LeetCode112. Path Sum(Easy)
- Path Sum && Path Sum ||
- Path Sum
- spring-redis的整合配置
- async和defer
- NIO与IO进行文件读取耗时对比,最近由于项目上用到IO操作,传统IO性能不佳
- 关于梯度下降算法的矢量化过程
- AngularJS与Angular的区别
- leetcode112. Path Sum
- Ajax的重构
- CTF数组越界漏洞内存布局简析
- Android studio 常用的插件
- 119. Pascal's Triangle II
- 跳台阶
- 对于bootstrap的个人理解
- Scrollview 嵌套 RecyclerView 及在Android 5.1版本滑动时 惯性消失问题
- 删除链表中的重复元素