劍指offer——二叉樹中和為某一值得路徑
阿新 • • 發佈:2019-01-01
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
private ArrayList<ArrayList<Integer>> arrayLists =
new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return arrayLists;
ArrayList<Integer> arrayList =
new ArrayList<>();
Find(root, 0, target, arrayList);
return arrayLists;
}
public void Find(TreeNode root, int sum, int target,
ArrayList<Integer> arrayList) {
TreeNode left = root.left;
TreeNode right = root.right;
if(sum + root.val > target) return;
if(sum + root.val == target && left == null && right == null ){
arrayList.add(root.val);
arrayLists.add((ArrayList<Integer>) arrayList.clone());
arrayList.remove(arrayList.size()-1);
return;
}
if(sum + root.val == target && !(left == null && right == null))return;
if(left != null) {
arrayList.add(root.val);
Find(root.left, sum + root.val, target, arrayList);
arrayList.remove(arrayList.size()-1);
}
if(right != null) {
arrayList.add(root.val);
Find(root.right, sum + root.val, target, arrayList);
arrayList.remove(arrayList.size()-1);
}
}
// public static void main(String[] args) {
// Solution solution = new Solution();
//
// TreeNode node1 = new TreeNode(1);
// TreeNode node2 = new TreeNode(2);
// TreeNode node3 = new TreeNode(3);
// TreeNode node4 = new TreeNode(4);
// TreeNode node5 = new TreeNode(5);
// TreeNode node6 = new TreeNode(7);
// TreeNode node7 = new TreeNode(8);
// TreeNode node8 = new TreeNode(4);
//
// node1.left = node2;
// node1.right = node3;
//
// node2.left = node4;
// node2.right = node5;
//
// node3.left = node6;
// node3.right = node7;
//
// node4.left = node8;
//
// List<ArrayList<Integer>> res = solution.FindPath(node1, 8);
//
// for(int i = 0; i < res.size(); ++i) {
// ArrayList<Integer> arrayList = res.get(i);
// for(int j = 0; j < arrayList.size(); ++j) {
// System.out.print(arrayList.get(j) + " " );
// }
// System.out.println();
// }
// }
}