劍指offer---二叉樹中和爲某一值的路徑(Java)

題目描述

輸入一顆二叉樹的根節點和一個整數,打印出二叉樹中結點值的和爲輸入整數的所有路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,數組長度大的數組靠前)

解析思路

在這裏插入圖片描述

實現代碼

public class Solution {
    private ArrayList<Integer> List = new ArrayList<Integer>();
    private ArrayList<ArrayList<Integer>> ListALL = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null) return ListALL;
        List.add(root.val);
        target -= root.val;
        if(target == 0 && root.left == null && root.right == null){
            ListALL.add(new ArrayList<Integer> (List));
        }
        FindPath(root.left, target);
        FindPath(root.right, target);
        List.remove(List.size() - 1);
        return ListALL;
    }
}

運行效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章