项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步
1.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
上面的题只需要判断是否有条路径的和为sum,而不需要求出所有的路径。
public static boolean findPathSum(TreeNode<Integer> root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.data == sum;
}
return (root.left != null && findPathSum(root.left, sum - root.data)) ||
(root.right != null && findPathSum(root.right, sum - root.data));
}
上面的代码,会沿着root先递归到最下面一个左子节点。假设此条路径就刚好满足和为sum,此时
if (root.left == null && root.right == null) {
return root.data == sum;
}
会返回true。那么root.left != null && findPathSum(root.left, sum - root.data)
会沿着堆栈信息一直回去返回true,后面的root.right != null && findPathSum(root.right, sum - root.data)
这行不再被执行!
如果中间任意一条路径的和刚好满足sum,具体的逻辑跟上面是一致的。
2.Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
这道题要求将路径和为sum的所有路径都数出来,那么至少需要将树的所有路径都遍历,同时判断每条路径的和,看是否等于sum。如果相等则输出。
import java.util.ArrayList;
import java.util.List;
/**
* Created by wanglei on 19/4/16.
*/
public class TreePathSum {
public static List<String> list = new ArrayList<>();
public static int target = 22;
public static TreeNode<Integer> init() {
TreeNode<Integer> root = new TreeNode<>(5);
TreeNode<Integer> node4 = new TreeNode<>(4);
TreeNode<Integer> node8 = new TreeNode<>(8);
TreeNode<Integer> node11 = new TreeNode<>(11);
TreeNode<Integer> node13 = new TreeNode<>(13);
TreeNode<Integer> node42 = new TreeNode<>(4);
TreeNode<Integer> node7 = new TreeNode<>(7);
TreeNode<Integer> node2 = new TreeNode<>(2);
TreeNode<Integer> node5 = new TreeNode<>(5);
TreeNode<Integer> node1 = new TreeNode<>(1);
root.left = node4;
root.right = node8;
node4.left = node11;
node8.left = node13;
node8.right = node42;
node11.left = node7;
node11.right = node2;
node42.left = node5;
node42.right = node1;
return root;
}
public static void findPathSum2(TreeNode<Integer> root, int sum, String path, List<String> res) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
if (sum == target) {
res.add(path);
}
return;
}
if (root.left != null) {
findPathSum2(root.left, sum + root.left.data, path + "->" + root.left.data, res);
}
if (root.right != null) {
findPathSum2(root.right, sum+root.right.data, path +"->" + root.right.data, res);
}
}
public static void printList(List<String> input) {
for(String ele: input) {
System.out.println(ele);
}
}
public static void main(String[] args) {
TreeNode<Integer> root = init();
findPathSum2(root, root.data, root.data.toString(), list);
printList(list);
}
}