劍指offer程式設計題(JAVA實現)——第24題:二叉樹中和為某一值的路徑
阿新 • • 發佈:2018-12-27
github | https://github.com/JasonZhangCauc/JZOffer |
---|
import java.util.ArrayList;
/**
*
* 劍指offer程式設計題(JAVA實現)——第24題:二叉樹中和為某一值的路徑
*
* 輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。
* 路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
* (注意: 在返回值的list中,陣列長度大的陣列靠前)
*
*/
public class Test24 {
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
if (root == null)
return arr;// 初始樹為空則返回
list.add(root.val);
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
// 避免listAll中所有引用都指向了同一個一個list重新new
arr.add(new ArrayList<Integer>(list));
}
if (root.left != null) {
FindPath(root.left, target);
}
if (root.right != null) {
FindPath(root.right, target);
}
list.remove(list.size() - 1);// 移除最後一個元素遞迴查詢
return arr;
}
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
}