描述

【算法】路径总和112

路径总和112II

分析

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.List;
import java.util.LinkedList;

//112. 路径总和
public class PathSum112 {
public static void main(String[] args){


TreeNode root = MyUtils.buildTree(
new Integer[]{5,4,8,11,null,13,4,7,2,null,null,null,1}
);
if (new Solution().hasPathSum(root, 22)) {
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}

class Solution {
//递归实现
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null ) return false;
//叶子节点
if (root.left == null && root.right == null) return root.val == targetSum;
//中间
return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
//路径总和II
class Solution2 {
List<List<Integer>> res;
LinkedList<Integer> path;
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {

res = new LinkedList<>();
path = new LinkedList<>();
travesal(root,targetSum);
return res;
}
private void travesal(TreeNode root, int count){
if (root == null) {
return;
}
path.offer(root.val);
count -= root.val;

//叶子节点
if (root.left == null && root.right == null && count == 0)
res.add(new LinkedList<>(path));
travesal(root.left, count);
travesal(root.right, count);
path.removeLast();//回溯
}
}


class TreeNode {
int val;
TreeNode left;
TreeNode right;

public TreeNode(){};
public TreeNode(int val){this.val = val;}
public TreeNode(int val, TreeNode left, TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}

class MyUtils {
/**
*二叉树的构建
* int[] -> 二叉树
*/
public static TreeNode buildTree(Integer[] arr) {
return buildTreeHelper(arr, 0);
}

public static TreeNode buildTreeHelper(Integer[] arr, Integer index) {
if (index >= arr.length || arr[index] == null) {
return null;
}

TreeNode node = new TreeNode(arr[index]);

node.left = buildTreeHelper(arr, 2 * index + 1);
node.right = buildTreeHelper(arr, 2 * index + 2);

return node;
}
}

总结