forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
73 lines (61 loc) · 1.95 KB
/
PathSum.java
File metadata and controls
73 lines (61 loc) · 1.95 KB
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
package com.leetcode.problems.medium;
import java.util.ArrayList;
import java.util.List;
/**
* @author neeraj on 05/09/19
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class PathSum {
static TreeNode root;
public static void main(String[] args) {
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);
System.out.println(pathSum(root, 22));
}
public static List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if (root != null) {
traverseTree(root, sum, 0, new ArrayList<>(), result);
}
return result;
}
public static void traverseTree(TreeNode root, int sum, int currentSum,
List<Integer> path, List<List<Integer>> result) {
if (root == null) {
return;
}
if (isLeaf(root)) {
if (sum == currentSum + root.val) {
// Cloning it.
path.add(root.val);
result.add(new ArrayList<>(path));
path.remove(path.size() - 1);
}
return;
}
path.add(root.val);
traverseTree(root.left, sum, currentSum + root.val, path, result);
traverseTree(root.right, sum, currentSum + root.val, path, result);
path.remove(path.size() - 1);
}
public static boolean isLeaf(TreeNode root) {
return root.left == null && root.right == null;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}