https://oj.leetcode.com/problems/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 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
解题思路:
题目要求找出二叉树根节点到所有叶节点路径的和,看看有没有和给定sum相等的。这种列举所有可能性的题目,和前面 Letter Combinations of a Phone Number 以及 Word Break II 的情况很像,用DFS的方法都可以求解。可以仔细体会一下这种针对树或者图的DFS和字符串DFS的对应联系。
于是,用一个DFS的方法,将所有可能的路径sum加入到一个set中,然后再看给定的sum在不在这个sum中即可。代码如下。
/** * 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) { Set<Integer> set = new HashSet<Integer>(); DFS(root, set, 0); return set.contains(sum); } public void DFS(TreeNode root, Set<Integer> set, int sum){ if(root == null){ return; } sum = sum + root.val; if(root.left == null && root.right == null){ set.add(sum); } DFS(root.left, set, sum); DFS(root.right, set, sum); // sum = sum - root.val; } }
上面的解法需要借助一个大小为O(logn)的set,下面是另一种思路,在DFS递归的过程中,如果遇到叶节点,就直接比较当前path的sum是不是和给定sum相等了。
虽然都是递归,但是思路和上一个方法却不一样。上面的递归没有返回值,单纯是计算path sum,最后放入到set中。这里递归返回一个boolean值,所以递归的入口是左右子树,有一个大path sum等于给定的sum,就返回true了,是或的关系。代码如下。
/** * 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 DFS(root, 0, sum); } public boolean DFS(TreeNode root, int sumTemp, int sum){ if(root == null){ return false; } sumTemp = sumTemp + root.val; if(root.left == null && root.right == null){ if(sumTemp == sum){ return true; } else{ return false; } } return DFS(root.left, sumTemp, sum) || DFS(root.right, sumTemp, sum); } }
//20181116
递归再简化
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return sum == root.val; } return hasPathSum(root.right, sum - root.val) || hasPathSum(root.left, sum - root.val); } }