劍指offer-24:二叉樹中和為某一值的路徑
阿新 • • 發佈:2018-12-07
題目描述
輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,陣列長度大的陣列靠前)
思路
dfs演算法
程式碼
public class Solution24 {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer> > ret = new ArrayList<>();
ArrayList<Integer> trace = new ArrayList<>();
if (root == null)
return ret;
pa(root, target, ret, trace);
return ret;
}
public void pa(TreeNode root, int target, ArrayList<ArrayList<Integer> > ret, ArrayList<Integer> trace) {
trace.add(root.val);
//若該結點是葉子結點則比較當前路徑和是否等於期待和。
if (root.left == null && root.right == null) {
if (target == root.val)
ret.add(new ArrayList<>(trace));
}
if (root.left != null)
pa(root.left, target - root.val, ret, trace);
if (root.right != null)
pa(root.right, target - root.val, ret, trace);
//彈出結點,每一輪遞迴返回到父結點時,當前路徑也應該回退一個結點
trace.remove(trace.size() - 1);
}
public static void main(String[] args) {
}
}