力扣每日一题,113. 路径总和 II
我的成绩
看这成绩,显然代码还需优化。不过我觉都我这种半吊子能过就很不错了,优化什么的,暂时去你的吧。
题目描述
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[ [5,4,11,2], [5,8,4,5] ]
思路
总之二叉树的题,就遍历了再说,十有八九是需要遍历的。
遍历模板
递归实现
public class Solution {
public static void main(String[] args) {
/*
* 5
* / \
* 4 3
* / \
* 1 2
*/
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(3);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(2);
new Solution().preOrder(root);
// 递归实现
}
void preOrder(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
提交代码
package 路径总和II;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
@Test
public void testPathSum() throws Exception {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.right.right.left = new TreeNode(5);
root.right.right.right = new TreeNode(1);
pathSum(root, 22);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> path = new LinkedList<Integer>();
List<List<Integer>> res = new LinkedList<List<Integer>>();
preOrder(root, 0, sum, path, res);
return res;
}
private void preOrder(TreeNode root,int num,int sum,List<Integer> path,List<List<Integer>> res) {
if(root!=null){
num+=root.val;
path.add(root.val);
if(root.left==null&&root.right==null&&num==sum){
System.out.println(path);
res.add(new ArrayList<Integer>(path));
}
// System.out.println(root.val);
preOrder(root.left, num,sum, path, res);
preOrder(root.right, num,sum, path, res);
path.remove(path.size()-1);
num-=root.val;
}
}
}